Exception Handling
Exception Handling
EXCEPTIONS
Synchronous Exception:
Out of rage
Over flow
Catch and
handle the
exception
EXCEPTION HANDLING MECHANISM (CONT…)
try
{
… // Block of statements //
which detect and throws an exception
throw exception;
…
}
catch(type arg)
{
…
…
…
}
EXCEPTION HANDLING MECHANISM (CONT…)
If the type of the object thrown matches the arg type in the catch statement, the
catch block is executed.
try
{
throw exception;
}
catch(type1 arg)
{
// catch block 1
}
catch(type2 arg)
{
// catch block 2
}
…
…
catch(typeN arg)
{
// catch block N
CATCHING MECHANISM (CONT…)
When an exception is thrown, the exception handlers are searched in order for a
match.
The first handler that yields a match is executed.
If several catch statement matches the type of an exception the first handler
that matches the exception type is executed.
Catch all exception
catch (…)
{
// statement for processing all exceptions
}
RETHROWING AN EXCEPTION
throw;
block
#include <iostream>
#include <stdexcept> cout << "Enter denominator: ";
cin >> denominator;
using namespace std;
try {
int divide(int numerator, int denominator) // Try to perform the division
{ result = divide(numerator, denominator);
if (denominator == 0) {
// Throw an exception if the // If successful, print the result
denominator is zero cout << "Result of division: " << result << endl;
throw runtime_error("Cannot divide } catch (const exception& e) {
by zero"); // Catch any exceptions that may occur
} cout << "Exception caught: " << e.what() <<
endl;
return numerator / denominator; } finally {
} // This block is optional and executes regardless
of whether an exception occurred or not
int main() { cout << "Finally block executed." << endl;
int numerator, denominator, result; }