Introduction
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.
}
File: except1.java
public class except1 { public static void main( String args[] ) { try { int x1 = 10 ; x1 = x1 / 0 ; } catch( Exception except ) { System.out.println( except.toString() ) ; } } }
C:\Java\exceptions>javac except1.java C:\Java\exceptions>java except1 java.lang.ArithmeticException: / by zeroThere is a slight disadvantage to the exception handling and that is the control movies to the catch block and it may be difficult to retry the function calls as we are out of the normal coding block.
The exception hierarchy starts with the "Throwable" class which is the base class for all exceptions. This has 2 subclasses "Error" and "Exception". The "Error"