Explain how exceptions are used for handling C++ error in a systematic and OOP-oriented way with the design that includes multiple exceptions.

This answer is restricted. Please login to view the answer of this question.

Login Now

Exceptions are run-time anomalies or abnormal conditions that a program encounters during its execution. Exception Handling in C++ is a process to handle runtime errors. We perform exception handling so the normal flow of the application can be maintained even after runtime errors. In C++, we use 3 keywords to perform exception handling: try, catch, and throw

  • The try statement allows us to define a block of code to be tested for errors while it is being executed.
  • The throw keyword throws an exception when a problem is detected, which lets us create a custom error.
  • The catch statement allows us to define a block of code to be executed, if an error occurs in the try block.

Syntax to handle multiple exceptions:

try
{
    //your code
} catch(exceptionName e1){
    // catch block
} catch(exceptionName e2){
    // catch block
} catch(exceptionName en){
    // catch block
}

The example of exception handling is

#include <iostream>
using namespace std;

int main(){

    int a = 3;

    try
    {
        if (a == 1)
            throw a; // throwing integer exception

        else if (a == 2)
            throw 'A'; // throwing character exception

        else if (a == 3)
            throw 4.5; // throwing float exception
    }
    catch (int a){
        cout << "\nInteger exception.";
    }catch (char ch){
        cout << "\nCharacter exception.";
    }catch (float f){
        cout << "\nFloat exception.";
    }
    cout << "\nProgram End.";

    return 0;
}

Output:

Float exception.
Program End
If you found any type of error on the answer then please mention on the comment or report an answer or submit your new answer.
Leave your Answer:

Click here to submit your answer.

Discussion
0 Comments
  Loading . . .