Exceptions
Contents
Procedural Style
In a procedural language the error handling is either done by
checking the return value of a function or checking some other
variable that contains the error. The pseudo code can look like:
result = function1() ;
if ( result < 0 )
//Handle error
function2() ;
if ( ErrorCode == 100 )
//Handle error
The code can easily become very messy. Another way to handle errors and this is
usually a feature in object oriented programming is to use Exceptions. The above
will instead look like:
try
{
result = function1() ;
function2() ;
}
catch ( Exception except )
{
//Any error in the try block causes control to come
//to the catch block.
}
The code that can "throw" an error is enclosed in a "try" block. Immediately
following the "try" block we have a "catch" block. In the "catch" block we
can handle the error. We need to have the "catch" following the "try" block else
we will get a compiler error. Both the "try" and "catch" work hand in hand.