Exception Handling
Exception Handling
EXCEPTIONS
try
{
… //Block of Statements which detects and
throw exception; // throw an exception
…
}
catch(type arg) //catch exception
{
… //Block of statements that handles exception
…
}
….
….
Example
#include <iostream>
using namespace std;
int main()
{ int x = -1; Output:
// Some code Before try
cout << "Before try \n"; Inside try
Exception Caught
try {
After catch (Will be executed)
cout << "Inside try \n";
if (x < 0)
{ throw x; //throw an exception
cout << "After throw (Never executed) \n";
}
} catch (int x ) {
cout << "Exception Caught \n"; }
cout << "After catch (Will be executed) \n";
return 0;}
Exception Handling
• Enclose code that may have an error in try block.
• Follow with one or more catch blocks. Each catch
block has an exception handler
• If exception occurs and matches parameter in
catch block, code in catch block executed
• If no exception thrown, exception handlers skipped
and control resumes after catch blocks
• throw point - place where exception occurred
Control cannot return to throw point
Exception Handling
• Exceptions are objects used to transmit
information about a problem.
• If the type of the object thrown matches the arg
type in the catch statement, the catch block is
executed.
Example
#include<iostream> catch(int i)
using namespace std; {
int main() cout<<“exception caught :
{int a,b; x = “<<x<<”\n”;
cout<<”Enter the values of a and }
b”; cout<<“End”;
cin>>a>>b; return 0;
int x = a- b; }
try First Run Output:
Enter the values of a and b
{ 20 15
if(x!=0) Result(a/x) =4
{cout<<“result(a/x) = End
Second Run Output:
“<<a/x<<”\n”; Enter the values of a and b
} 10 10
else{ exception caught : x =0
End
throw(x);}}
Exception Handling
• Often, Exceptions are thrown by functions that are
invoked from within the try blocks.
• The point at which the throw is executed is called
the throw point.
• Once an exception is thrown to the catch block,
control cannot return to the throw point.
// The try block is immediately followed by the catch block, irrespective of the location of throw point