Exception Handling in C++

Exception:

An unwanted state during the execution of the program. It can also be defined as “errors at run-time”. 
For example, 
Dividing a number by zero.

Whenever there is an exception in the program, the programmer has two possible solutions: 

a)Resumption- fix the problem and continue
b)Termination-Abort the process and return

In C++,
the Resumption model is supported by the function call mechanism, and 
the Termination model is supported by the exception-handling mechanism

Exception Handling:

“Exception Handling” allows us to manage the exception gracefully. 
Using Exception Handling technique we can avoid abnormal termination of the program and continue with the normal flow or the program, or even move the control to other parts of the program.

Exceptions are handled using try catch statements.

General syntax: 
try{ 

statements;
. . . . . 


catch(type1 arg){statements;}

catch(type2 arg){statements;}

•We can have more than one catch statement associated with a try.


Exception Handling Example:

#include<iostream.h>
void main()

      int j; 
      cin>>j; 
      try
      { 
            if(j==0) throw j; 
               int i=20/j; 
      }catch(int j){ 
            cout<<"Divide by zero"; 
      }catch(...){ 
            cout<<"Caught Exception"; 
      }
}

Output: 
Divide by zero

Re-throwing an Exception:

A re-throw is indicated by a throw without an operand. 

Example;
try{ 
      //code which throws error 
}catch(Error e){ 
      throw; //re-throw 

If a re-throw is attempted when there is no exception to throw , terminate() will be called. 
terminate(), by default, calls abort() to stop the program. But we can specify our own termination handler.

Custom Exception Class:

#include<iostream.h> 
#include<string.h> 

class MyException

{           char *msg; 
          public: 
                  MyException(){
                          msg="MyException";
                  } 
                  MyException(char *m) 
                  {
                          msg=m;
                  } 
                  char* getMessage(){ 
                          return msg;
                  } 

};

void main() 

       int age; 
       try{ 
              cout<<"Enter your age"; 
              cin>>age; 
              if(age>18) 
                     cout<<"Ready to vote"; 
              else{ 
                     MyException e("You are Minor!!"); 
                     throw e;
              } 
       } 
       catch(MyException e) 
       { 
              cout<<"Exception"<<e.getMessage(); 
       }
}

No comments:

Post a Comment