Object Oriented Programming With C+ +: Chapter - 13
Object Oriented Programming With C+ +: Chapter - 13
Programming With C+
+
Chapter -13
Exception handling
Exception
Exceptions are runtime anomalies or an unusual
condition that a program may face.
Exceptions are neither syntax error nor logical error.
In C++ following key-words are used to handle
exception.
1. Try : block that may rise exception.
2. Throw : visually written inside the try block.
3. Catch : handling/catching the exception thrown by the
throw statement.
When throw is true, catch is called.
input output
Example
int main()
3 66
{
end
int m;
cin>>m;
0 exception occurred for: 0
try {
end
if(m==0) throw m;
cout<<200/m<<endl;
}
catch(int x)
{
cout<<"exception int occured for:"<<x<<endl;
}
catch(double d)
{
cout<<"exception for double"<<d<<endl;
}
cout<<"end\n";
return 0;
}
Multiple catch block
A try block must be followed by at least one
catch block (otherwise compiler error occurs).
If there are more than one catch block then the
catch which meets the data type is executed.
If there is no catch for a corresponding throw
then following system functions are called.
Terminate() -> abort()
Catching all exceptions
catch(…)
{
cout<<“catching all data types\n”;
}
This special catch block should be the last
among all catch blocks in a try-catch
family.
input output
Example
int main()
3 exception for all
{
end
int m;
cin>>m;
0 exception occurred for: 0
try {
end
if(m==0) throw m;
else throw ‘a’;
}
catch(int x)
{
cout<<"exception int occured for:"<<x<<endl;
}
catch(…)
{
cout<<"exception for all”<<endl;
}
cout<<"end\n";
return 0;
}
Invoking function that generates exception
void test(int x)
{
input Output
if(x==0) throw 1;
if(x==1) throw 1.0;
throw 'x';
} 0 Catch all
int main() end
{ 5 Catch all
int n;
cin>>n; end
try{
test(n);
cout<<"exiting try\n";
}
catch(...)
{
cout<<"catch all\n";
}
cout<<"end\n";
return 0;
}
Restricting the invoking function that generates exception
void test(int x) throw(int,double)
{
if(x==0) throw 1;
if(x==1) throw 1.0; Input Output
}
int main()
1.0 Catch all
{
int n; end
cin>>n; x Exiting try
try{ end
test(n);
cout<<"exiting try\n";
}
catch(...){
cout<<"catch all\n";
}
cout<<"end\n";
return 0;
}
Restricting the invoking function
that generates exception
If throw() is used then it will not throw
anything.
If throw() is not written then it will throw all.