C++ Exception Handling Basics
C++ Exception Handling Basics
It is very rare that a program works correctly first time. It might have bugs. The two
most common types of bugs are logical errors and syntactic errors.
The logic errors occur due to poor understanding of the problem and solution
procedure.
The syntactic errors arise due to poor understanding of the language itself.
We can detect these errors by using exhaustive debugging and testing procedures.
There are some other problems other than logic or syntax error known as
exceptions. Exceptions are run time anomalies or unusual conditions that a program
may encounter while executing.
Errors such as ‘out of range index’ and ‘over flow’ belong to the synchronous
exceptions.
The errors that are caused by event beyond the control of the program (such as
keyboard interrupts) are called asynchronous exceptions.
The error handling code basically consists of two segment, one to detect
errors and to throw exceptions, and the other to catch the exception and to
take appropriate actions.
When try blocks throws an exception, the program control leaves the try block and
enters the catch statement of the catch block.
If the types of object thrown matches the arg type in the catch statement, then
catch block is executed for handling the exception.
If they do not match, the program is aborted with the help of abort() function
which is invoked by default.
When no exception is detected and thrown, the control goes to the statement
immediately after the catch block (The catch block is skipped).
#include <iostream>
using namespace std;
int main()
{
try
{
int age = 15;
if (age >= 18) {
cout << "Access granted - you are old enough.";
} else {
throw (age);
}
}
catch (int myNum) {
cout << "Access denied - You must be at least 18 years old.\n";
cout << "Age is: " << myNum;
}
return 0;
}
Throwing Mechanism
When an exception that is desired to be handled is detected, it is thrown using the
throw statement in one of the following forms:
throw (exceptions);
throw exceptions;
Catching Mechanism:
Code for handling exception is included in the catch blocks. A catch block look like
a function definition and is of the form
{
//statements for
// managing exceptions
}
The type indicates the type of exception that catch block handles. The parameter
argument is an optional parameter name. The exception handling code is placed
between two braces. The catch statement catches an exception whose type
matches with type of catch argument. When it is caught, the code in the catch
block is executed.
try
// try block
catch(type1 arg)
//catch block 1
catch(type2 arg)
//catch block2
…….
……
catch(typeN arg)
//catch block n)
When an exception is thrown, the exception handler are searched in order for an
appropriate match. The first handler that yields a match is executed. When no match
is found, the program is terminated.