Exception Handling
1./* Try Block Throwing Exception */
int main()
{
int a,b;
cout<<"Enter a , b";
cin>>a>>b;
try
{
if(b!=0)
cout<<"Division Result = "<<a/b<<endl;
else
throw(b);
}
catch(int b) { cout<<"Exception Caught : b ="<<b<<endl; }
cout<<"End";
return(0);
}
2./* Invoking Function that generates Exception */
void division(int x,int y)
{
cout<<"\n Inside Function\n";
if(y!=0) { cout<<"Result="<<x/y<<endl; }
else { throw(y); }
}
int main()
{
try
{
cout<<"\nTry Block:\n";
division(10,5);
division(3,0);
}
catch(int i) { cout<<"\n Caught The Exception \n"; }
cout<<"End";
return(0);
}
3./* Multiple catch statements */
void multi_catch(int x)
{
try
{
if(x==1) throw x;
else if (x==0) throw 'a';
else if (x==-1) throw 1.5;
cout<<"TryBlock"<<endl;
}
catch(char c) { cout<<"Caught a character"<<c<<endl; }
catch(int p) { cout<<"Caught an integer"<<a<<endl; }
catch(float f) { cout<<"Caught a float value"<<f<<endl; }
cout<<"End of Try Catch Block"<<endl;
}
int main()
{
multi_catch(1);
multi_catch(0);
multi_catch(-1);
multi_catch(2);
cout<<"End";
return(0);
}
4./* Catching all exceptions */
void multi_catch(int x)
{
try
{
if(x==1) throw x;
else if (x==0) throw 'a';
else if (x==-1) throw 1.5;
cout<<"TryBlock"<<endl;
}
catch(...) { cout<<"Caught an Exception"<<endl; }
cout<<"End of Try Catch Block"<<endl;
}
int main()
{
multi_catch(1);
multi_catch(0);
multi_catch(-1);
multi_catch(2);
cout<<"End";
return(0);
}
5./* Catching all exceptions */
void multi_catch(int x)
{
try
{
if(x==1) throw x;
else if (x==0) throw 'a';
else if (x==-1) throw 1.5;
cout<<"TryBlock"<<endl;
}
catch(int p) { cout<<"Caught An integer "<<p<<endl; }
catch(...) { cout<<"Caught an Exception"<<endl; }
cout<<"End of Try Catch Block"<<endl;
}
int main()
{
multi_catch(1);
multi_catch(0);
multi_catch(-1);
multi_catch(2);
cout<<"End";
return(0);
}
// catch(...) should always be placed last in the list of handlers. Placing it before other
catch blocks prevents those blocks from catching exceptions
6./* Rethrowing An Exception */
void division(int x,int y)
{
cout<<"\n Inside Function\n";
if(y!=0){ cout<<"Result="<<x/y<<endl;}
else{throw(y);}
catch(int m){ cout<<"Caught divisor value as 0 inside the function"<<endl; throw; }
}
int main()
{
try
{
cout<<"\nTry Block:\n";
division(10,5);
division(3,0);
}
catch(int i)
{
cout<<"\n Caught inside main \n";
}
cout<<"End";
return(0);
}
7./* Specifying Exceptions */
void multi_catch(int x) throw(int,float)
{
if(x==1) throw x;
else if (x==0) throw 'a';
else if (x==-1) throw 1.5;
cout<<"TryBlock"<<endl;
}
int main()
{
clrscr();
try
{
multi_catch(1);
multi_catch(0);
multi_catch(-1);
multi_catch(2);
}
catch(int p) { cout<<"\n Caught an integer"<<endl; }
catch(char c) { cout<<"\n Caught a character"<<endl; }
catch(float q) { cout<<"\n Caught a float"<<endl; }
cout<<"End";
return(0);
}