Exceptions: An OO Way for Handling Errors Introduction Rarely does a program runs successfully at its very first attempt. It is common to make mistakes while developing as well as typing a program. Such mistakes are categorised as: syntax errors - compilation errors. semantic errors leads to programs producing unexpected outputs. runtime errors most often lead to abnormal termination of programs or even cause the system to crash. 1 2 Common Runtime Errors Without Error Handling Example 1 Dividing a number by zero. Accessing an element that is out of bounds of an array. Trying to store incompatible data elements. Using negative value as array size. Trying to convert from string data to a specific data value (e.g., converting string abc to integer value). File errors: opening a file in read mode that does not exist or no read permission Opening a file in write/update mode which has read only permission. Corrupting memory: - common with pointers Any more. 3 class NoErrorHandling public static void main(string[] args) int a,b; a = 7; b = 0; Program does not reach here System.out.println( Result is + a/b); System.out.println( Program reached this line ); No compilation errors. While running it reports an error and stops without executing further statements: java.lang.arithmeticexception: / by zero at Error2.main(Error2.java:10) 4 Traditional way of Error Handling - Example 2 class WithErrorHandling public static void main(string[] args) int a,b; a = 7; b = 0; if (b!= 0) System.out.println( Result is + a/b); else Program reaches here System.out.println( Program is complete ); 5 Error Handling Any program can find itself in unusual circumstances Error Conditions. A good program should be able to handle these conditions gracefully. Java provides a mechanism to handle these error condition - exceptions 6
Exceptions Exceptions and their Handling An exception is a condition that is caused by a runtime error in the program. Provide a mechanism to signal errors directly without using flags. Allow errors to be handled in one central part of the code without cluttering code. 7 When the JVM encounters an error such as divide by zero, it creates an exception object and throws it as a notification that an error has occurred. If the exception object is not caught and handled properly, the interpreter will display an error and terminate the program. If we want the program to continue with execution of the remaining code, then we should try to catch the exception object thrown by the error condition and then take appropriate corrective actions. This task is known as exception handling. 8 Common Java Exceptions ArithmeticException ArrayIndexOutOfBoundException ArrayStoreException FileNotFoundException IOException general I/O failure NullPointerException referencing a null object OutOfMemoryException SecurityException when applet tries to perform an action not allowed by the browser s security setting. StackOverflowException StringIndexOutOfBoundException 9 Exceptions in Java Java exception handling is managed via five keywords: try, catch, throw, throws, and finally. try block: Program statements that you want to monitor for exceptions are contained within a try block. catch block: If an exception occurs within the try block, it is thrown. Your code can catch this exception (using catch) and handle it in some rational manner. throw: System-generated exceptions are automatically thrown by the Java run-time system. To manually throw an exception, use the keyword throw. trows: Any exception that is thrown out of a method must be specified as such by a throws clause. finally: Any code that absolutely must be executed after a try block completes is put in a finally block. 10 Exception Handling Mechanism Throws exception try Block Statements that causes an exception catch Block Statements that handle the exception 11 Throwing, Catching, Continuation Built-in exceptions will be thrown automatically if the exception arises User-defined exceptions are thrown explicitly through a throw statement (Same as in C++) built-in exceptions can also be thrown explicitly The catch block that catches an exception is based on the type of exception, not on a parameter type exceptions can be handled in the given block or are propagated if the method explicitly states throws ExceptionType in its header, in which case the exception is propagated to the caller this can continue until the main program is reached in which case, if not handled, the program terminates
General Form of Exception Handling Block try // block of code to monitor for errors catch (ExceptionType1 exob) // exception handler for ExceptionType1 catch (ExceptionType2 exob) // exception handler for ExceptionType2 //. finally // block of code to be executed after try block ends Here, ExceptionType is the type of exception that has occurred. With Exception Handling - Example 3 class WithExceptionHandling public static void main(string[] args) int a,b; float r; a = 7; b = 0; try r = a/b; System.out.println( Result is + r); Program Reaches here catch(arithmeticexception e) System.out.println( Program reached this line ); 13 14 Multiple Catch Statements If a try block is likely to raise more than one type of exceptions, then multiple catch blocks can be defined as follows: try // statements catch( Exception-Type1 e) // statements to process exception 1 catch( Exception-TypeN e) // statements to process exception N 15 Run-1 Example C:\>java MultiCatch a = 0 class MultiCatch Divide by 0: public static void main(string args[]) java.lang.arithmeticexception: / by zero try int a = args.length; After try/catch blocks. System.out.println("a = " + a); Run-2 int b = 42 / a; C:\>java MultiCatch TestArg int c[] = 1 ; a = 1 c[42] = 99; Array index oob: java.lang.arrayindexoutofbo catch(arithmeticexception e) undsexception:42 After try/catch blocks System.out.println("Divide by 0: " + e); catch(arrayindexoutofboundsexception e) System.out.println("Array index oob: " + e); System.out.println("After try/catch blocks."); 16 class NestTry public static void main(string args[]) try int a = args.length; int b = 42 / a; System.out.println("a = " + a); try // nested try block if(a==1) a = a/(a-a); // division by zero if(a==2) Int c[] = 1 ; c[42] = 99; Nested Try C:\>java NestTry Divide by 0: java.lang.arithmeticexception: / by zero C:\>java NestTry One a = 1 Divide by 0: java.lang.arithmeticexception: / by zero C:\>java NestTry One Two a = 2 Array index out-of-bounds: java.lang.arrayindexoutofboundsexception:42 catch(arrayindexoutofboundsexception e) System.out.println("Array index out-of-bounds: " + e); catch(arithmeticexception e) System.out.println("Divide by 0: " + e); 17 Finally, Continuation Aside from the throw and catch clauses, Java allows a finally clause The finally clause can be a clean up set of code for the object that is, if any exception arises, there might need to be some routine that makes sure the object can continue The finally clause is always executed prior to continuation whether an exception arises or not and regardless of the type of exception Continuation occurs with the statement after the Try construct if there is none, then continuation occurs with the caller of the method and so forth up the run-time stack ultimately, if no method is found, continuation occurs with the original application program or termination
finally block Exception Classes Java supports definition of another block called finally that be used to handle any exception that is not caught by any of the previous statements. It may be added immediately after the try block or after the last catch block: try // statements catch( Exception-Type1 e) // statements to process exception 1 finally. When a finally is defined, it is executed regardless of whether or not an exception is thrown. Therefore, it is also used to perform certain house keeping operations such as closing files and releasing system resources. 19 Throwable Exception Error ClassNotFoundException IOException AWTException RuntimeException LinkageError VirtualMachineError AWTError ArithmeticException NullPointerException IndexOutOfBoundsException IllegalArgumentException 20 System Errors Exceptions Throwable Exception ClassNotFoundException IOException AWTException RuntimeException ArithmeticException NullPointerException IndexOutOfBoundsException IllegalArgumentException Exception describes errors caused by your program and external circumstances. These errors can be caught and handled by your program. Throwable Exception ClassNotFoundException IOException AWTException RuntimeException ArithmeticException NullPointerException IndexOutOfBoundsException IllegalArgumentException System errors are thrown by JVM and represented in the Error class. The Error class describes internal system errors. Such errors rarely occur. If one does, there is little you can do beyond notifying the user and trying to terminate the program gracefully. Error LinkageError VirtualMachineError AWTError Error LinkageError VirtualMachineError AWTError 21 22 Checked and Unchecked Exception Unchecked Exceptions: compiler does not check to see if a method handles or throws these exceptions. Example: NullPointerException or any class extending the RuntimeException class. Checked Exceptions: Exceptions which are checked for during compile time are called checked exceptions. (that must be included in a method s throws list if that method can generate one of these exceptions and does not handle it itself) All the checked exceptions must be handled in the program. The exceptions raised, if not handled will be handled by the Java Virtual Machine. The Virtual machine will print the stack trace of the exception indicating the stack of exception and the line where it was caused Example: SQLException or any userdefined exception extending the Exception class Example public class myexception public static void main(string args[]) try File f = new File( myfile ); FileInputStream fis = new FileInputStream(f); catch(filenotfoundexception ex) File f = new File( Available File ); FileInputStream fis = new FileInputStream(f); finally // the finally block //continue processing here. In this example we are trying to open a file and if the file does not exists we can do further processing in the catch block. The try and catch blocks are used to identify possible exception conditions. We try to execute any statement that might throw an exception and the catch block is used for any exceptions caused. If the try block does not throw any exceptions, then the catch block is not executed. The finally block is always executed irrespective of whether the exception is thrown or not.
With Exception Handling - Example 4 With Exception Handling - Example 5 class WithExceptionCatchThrow public static void main(string[] args) int a,b; float r; a = 7; b = 0; try r = a/b; System.out.println( Result is + r); Program Does Not reach here when exception occurs catch(arithmeticexception e) throw e; System.out.println( Program is complete ); 25 class WithExceptionCatchThrowFinally public static void main(string[] args) int a,b; float r; a = 7; b = 0; try r = a/b; System.out.println( Result is + r); Program reaches here catch(arithmeticexception e) throw e; finally System.out.println( Program is complete ); 26 User-Defined Exceptions Defining your own exceptions Problem Statement : Consider the example of the Circle class Circle class had the following constructor public Circle(double centrex, double centrey, double radius) x = centrex; y = centrey; r = radius; How would we ensure that the radius is not zero or negative? import java.lang.exception; class InvalidRadiusException extends Exception private double r; public InvalidRadiusException(double radius) r = radius; public void printerror() System.out.println("Radius [" + r + "] is not valid"); 27 28 class Circle double x, y, r; Throwing the exception public Circle (double centrex, double centrey, double radius ) throws InvalidRadiusException if (r <= 0 ) throw new InvalidRadiusException(radius); else x = centrex ; y = centrey; r = radius; Catching the exception class CircleTest public static void main(string[] args) try Circle c1 = new Circle(10, 10, -1); System.out.println("Circle created"); catch(invalidradiusexception e) e.printerror(); 29 30
User-Defined Exceptions in standard format Summary class MyException extends Exception MyException(String message) super(message); // pass to superclass if parameter is not handled by used defined exception class TestMyException try throw new MyException( This is error message ); catch(myexception e) System.out.println( Message is: +e.getmessage()); Get Message is a method defined in a standard Exception class. 31 A good programs does not produce unexpected results. It is always a good practice to check for potential problem spots in programs and guard against program failures. Exceptions are mainly used to deal with runtime errors. Exceptions also aid in debugging programs. Exception handling mechanisms can effectively used to locate the type and place of errors. 32 Summary Try block, code that could have exceptions / errors Catch block(s), specify code to handle various types of exceptions. First block to have appropriate type of exception is invoked. If no local catch found, exception propagates up the method call stack, all the way to main() Any execution of try, normal completion, or catch then transfers control on to finally block 33