Exception Handling
Exception Handling
Topics
• Introduction
• Why we need?
• Types
• C++ standard exceptions
• Constructors
• Destructors
Introduction
• Exception handling in C++.
• Exception means an unexpected problem that arises during the
execution of the program.
• Exception handling provides a way to transfer control from
one part of the program to other part.
Why we need exception handling
#include<iostream>
• Graceful exit using namespace std;
• Meaningful message to caller zero(int a,int b)
{
• Abnormal termination return(a/b);
};
int main()
{
int A=2;
int B=0;
int result;
result=zero(A,B);
cout<<"the result
is"<<result<<endl;
return 0;
}
Types
• Synchronous
• Asynchrounus
Synchronous
Try
Catch
Syntax:
try
{
// protected code
}
catch ( ExceptionName e1 )
{
// catch block
}
catch ( ExceptionName e2 )
{
// catch block
}
catch ( ExceptionName eN )
{
// catch block
}
There is a special catch block called ‘catch all’ catch(…) that can be used to catch all types of exceptions.
Throw
Syntax:
double division(int a, int b)
{
if( b == 0 )
{
throw "Division by zero condition!";
}
return (a/b);
}
#include <iostream>
using namespace std;
int main () {
int x = 50;
int y = 0;
double z ;
try {
z = division(x, y);
cout << z << endl;
} catch (const char* msg) {
cerr << msg << endl;
}
return 0;
}
C++ standard exceptions
User-Defined Exceptions
• The C++ std::exception class permits us to define
objects that can be thrown as exceptions. This class is
defined in the <exception> header. The class gives us
a virtual member function named what.
• This function returns an invalid ended character
sequence of type char*. We can overwrite it in
determined classes to have an exception depiction.
• We can overwrite the ‘what() function’ of the
exception header file to define our exceptions.
Exception handling in constructors
Exception handling in destructors
1. No, It's not a good idea.
2. Destructor are by default noexcept.
std::terminate
3. The Stack unwinding will happen after an exception and we may catch it outside.
throw Foo()
and the
}
catch (Foo e)
{
References
• http://www.cplusplus.com/forum/general/25
3853
/
• https://www.geeksforgeeks.org/exception-ha
ndling-c
/
Q&A