EXCEPTION HANDLING


Exception Handling allows programmers to make the program ready for any errors that may happen during execution and handle them gracefully so that it keeps running without errors.

Types of Exceptions:

a) It is an exception handling mechanism when the code that may cause an exception is placed inside the try block and the code that handles the exception is placed inside the catch block.
b) The "throw" keyword is used to throw the exception.
c) The what() method present in every standard exception provides information about the exception.
d) catch(...) creates a catch-all block which is executed when none of the catch statements are matched.

Catching exceptions by value creates a new copy of the thrown object in the catch block.

Catch by Reference method just pass the reference to the exception thrown instead of creating a copy.  The main advantage of the method is in catching polymorphic exception type.

If the exception is not caught by any of the catch block, then by default, the exception handling subsystem aborts the execution of the program.

Custom Exceptions:
we can catch custom exceptions by creating custom exception class inherited from the standard exception class.

Example:

#include <iostream>
using namespace std;

class CustomException : public exception
{
public:
int what()
{
cout<<"Custom Exception"<<endl;
return -2;
}
};

int main()
{
try
{
int choice;
cout<<"Enter 1 for integer exception, "
<<" 2 for out_of_range exception, "
<<" 3 for invalid_argument exception, "
<<" 4 for runtime_error exception, "
<<" 5 for CustomException"<<endl;
cin>>choice;

if(choice == 1)
throw -1;
else if(choice == 2)
throw out_of_range("Out of Range Exception");
else if(choice == 3)
throw invalid_argument("Invalid Argument Exception");
else if(choice == 4)
throw runtime_error("Runtime Exception");
else if(choice == 5)
throw CustomException("Custom Exception");
else
throw "Unknown Error";
}
catch(int e)
{
cout<<"Integer Exception: "<<e<<endl;
}
catch(out_of_range e)
{
cout<<"Caught Exception: "<<e.what()<<endl;
}
catch(invalid_argument e)
{
cout<<"Caught Exception: "<<e.what()<<endl;
}
catch(runtime_error e)
{
cout<<"Caught Exception: "<<e.what()<<endl;
}
catch(CustomException e)
{
cout<<"Caught Exception: "<<e.what()<<endl;
}
catch(...)
{
cout<<"Caught an Unknown Exception"<<endl;
}
}

Popular posts from this blog

OBJECT ORIENTED ANALYSIS AND DESIGN (OOAD)

OBJECT ORIENTED PROGRAMMING

STARTING A BUSINESS