Introduction to Exception


Exception

An exception is a problem that arises during the execution of a program

It is a run-time error that a program may detect

The response given to the problems occurred during the execution of the program

Exception handling allows the program to continue execution

Helps to identify the problem

Terminates the program in a controlled manner

 

Types of Exception Handling

Try

Catch

Throw

 

Syntax 

throw;

try

{ //try blocks starts

............

} //try block ends

catch (arg)

{ //catch block starts

............

} //catch block ends

 

Ex:-


#include <iostream>
using namespace std;

double division(int a, int b)
{
   if( b == 0 )
   {
//the message shows when exception occur       
throw "Division 1 by zero condition!";
   }
   return (a/b);
}

int main ()
{
int x,y;
double z;
cout<<"Enter value of x and y\n";
cin>>x>>y;
   try
    {
     z = division(x, y);
     cout << z<<"\n";
    }
catch (const char* msg)
    {
     cout << msg << endl;
   }
   return 0;
}

Output:-   Enter the value of x and y

5

0

Division 1 by zero condition!

 

0 Comments