An Autonomous Institution: Course Name: Object Oriented Programming
An Autonomous Institution: Course Name: Object Oriented Programming
Coimbatore-35.
An Autonomous Institution
Accredited by NBA – AICTE and Accredited by NAAC – UGC with ‘A+’ Grade
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Mr.M.Karthick
Assistant Professor
Department of Computer Science and Engineering
Exception Handling
Definition
• An exception is a problem that arises during the execution of a program. A C++
exception is a response to an exceptional circumstance that arises while a
program is running.
• Exceptions provide a way to transfer control from one part of a program to
another. C++ exception handling is built upon three keywords: try,
catch,and throw.
• Example: attempt to divide by zero.
• throw − A program throws an exception when a problem shows up. This is done
using a throw keyword.
• catch − A program catches an exception with an exception handler at the place in
a program where you want to handle the problem. The catch keyword indicates
the catching of an exception.
• try − A try block identifies a block of code for which particular exceptions will be
activated. It's followed by one or more catch blocks.
Syntax
try
{
//code
throw parameter;
}
catch(exceptionname ex)
{
//code to handle exception
}
Example cout <<"enter two integer values";
#include <iostream> cin>>x>>y;
using namespace std; double z = 0;
double division(int a, int b) try
{ {
if( b == 0 ) z = division(x, y);
{ cout << z << endl;
throw "Division by zero condition!"; }
} catch (const char* msg)
return (a/b);
{
}
cerr << msg << endl;
int main ()
}
{
return 0;
int x;
}
int y;
Output
Multiple Exceptions
References
1. Robert Lafore, Object Oriented Programming in-C++, Galgotia Publication, 2009.
2. Deitel & Deitel, “C++ How to program”, Prentice Hall,2005.
3. D.S.Malik, “C++ Programming”, Thomson, 2007.
4. K.R.Venugopal, Rajkumar and T.Ravishankar, “Mastering C++”, Tata McGraw Hill
Publishing Co. Ltd., New Delhi, 2006.
5. E.Balagurusamy, “Object Oriented Programming with C++”, Sixth Edition, McGraw
Hill Education ,2013.