EXCEPTION HANDLING OR ERROR HANDLING
- Error means mistakes or buggs - Error is classified into types What is Error? - Error means mistakes or buggs - Error is classified into types Error Compile Time Error Run Time Error All syntax errors will be detected And displayed by the Java compi ler and therefore these errors Are known as compile – time – errors A program may compile success fully creating the .exe file but not run properly. Such programs may produce wrong results due to wrong loaic or may terminate due to errors Missing Semicolon Missing brackets in classes and methods 3. Use of undeclared variables Dividing an integer by zero Accessing an element that is out of the bounds of an array
Some Example of Runtime Errors class Error_Handling { public static void main(String args[]) int a,b,c; a = 10; b = 0; c = a / b; System.out.println("The Value of the C Value is:" + c); } Output: / by zero
Exception Types Throwable Exception (or) RuntimeException Error 1. All Exception types are subclasses of the built – in class Throwable. Throwable is at the top of the exception class hierarchy Throwable Exception (or) RuntimeException Error This class is used for exceptional conditions that user programs should catch. This is also the class That you will subclass to create your own custom exception types Which defines exceptions that are not Expected to be caught under normal Circumstances by our program. Ex. Stack overflow
Uncaught Exception class Error_Handling { public static void main(String args[]) int i,j,k1,k2; i = 10; j = 0; k1 = i / j; k2 = i + j; System.out.println("The Division of the K1 Value is: " + k1); System.out.println("The addition of the K2 Value is: " + k2); } Output: java.lang.ArithmeticException: / by zero at Error_Handling.main(Error_Handling.java:4) In this example, we haven’t supplied any exception handlers of our own, so the exception is caught by the default handler provided by the java run – time system
What is Exceptions? An Exception is condition that is caused by a run – time error in the program. What is Exception Handling? If the exception object is not caught and handled properly, the compiler will display an error message and will terminate the program. If we want the program to continue with the execution of the remaining appropriate message for taking corrective actions. This task is known as exception handling. Exceptions Types Exception Asynchronous Exception Synchronous Exception Keyboard Interrupt Mouse Interrupt Division by Zero
Catches and handles the Exception Handling Mechanism The purpose of the exception handling mechanism is to provide means to detect and report an “exceptional circumstance”, so that appropriate action can be taken. The Error Handling code that performs the following tasks: 1. Find the problem (Hit the Exception) 2. Inform that an error has occurred (Throw the exception) 3. Receive the error information (Catch the exception) 4. Take corrective actions (Handle the exception) try block Detects and throws an exception catch block Catches and handles the exception Exception object
Using try and catch //Block of statements which detects and ------------------ try { ------------- } catch(Exception_Type e) -------------- //Block of statements which detects and //throws an exception //Catches exception //Block of statements that handles the //exception
Example Program for Exception Handling Mechanism class Error_Handling { public static void main(String args[]) int i,j,k1,k2; i = 10; j = 0; try k1 = i / j; System.out.println("The Division of the K1 Value is: " + k1); } catch(ArithmeticException e) System.out.println("Division by Zero"); k2 = i + j; System.out.println("The addition of the K2 Value is: " + k2); There is an Exception Catches the exception Output: Division by Zero, The addition of the K2 Value is:10
Multiple Catch Statements It is possible that a program segment has more than one condition to throw an exception. try { //statements } catch(Exception-Type-1 e) catch(Exception-Type-2 e) ----------- catch(Exception-Type-N e)
class Error_Handling { public static void main(String args[]) int a[ ] = {5,10}; int b = 5; try int x = a[2] / b - a[1]; } catch(ArithmeticException e) System.out.println("Division by Zero"); catch(ArrayIndexOutOfBoundsException e) System.out.println("Array Index Error"); catch(ArrayStoreException e) System.out.println("Wrong data type"); int y = a[1] / a[0]; System.out.println("Y = " + y);
COMMAN EXCEPTION HANDLER class Error_Handling { public static void main(String args[]) int a[ ] = {5,10}; int b = 5; try int x = a[2] / b - a[1]; } catch(ArithmeticException e) System.out.println("Division by Zero"); /*catch(ArrayIndexOutOfBoundsException e) System.out.println("Array Index Error"); }*/ catch(ArrayStoreException e) System.out.println("Wrong data type");
catch(Exception e) { System.out.println("The Producing any Runtime Error" + e.getMessage()); } int y = a[1] / a[0]; System.out.println("Y = " + y);
EXCEPTION HIERARCHY class Error_Handling { public static void main(String args[]) int a[ ] = {5,10}; int b = 5; try int x = a[2] / b - a[1]; } catch(ArithmeticException e) System.out.println("Division by Zero"); catch(Exception e) System.out.println("The Producing any Runtime Error" + e.getMessage()); /*catch(ArrayIndexOutOfBoundsException e) System.out.println("Array Index Error"); }*/
catch(ArrayStoreException e) { System.out.println("Wrong data type"); } int y = a[1] / a[0]; System.out.println("Y = " + y);
Nested try Statements class Error_Handling { public static void main(String args[]) try int a = args.length; int b = 42 / a; //If no command - line args are present, //the following statement will generate a divide - by - zero exception System.out.println("a = " + a); // nested try bloack // If one command - line arg is used, then a divide - by //- zero exception will be generated by the following code.
try { if ( a == 1) a = a / (a - a); //division by zero if(a == 2) int c[] = {1}; c[42] = 99; //generate an out - of - bounds exception } catch(ArrayIndexOutOfBoundsException e) System.out.println("Array index out - of - bounds: " + e); catch(ArithmeticException e) System.out.println("Divide by Zero: " + e);
Nested try Statements using Subroutine class Error_Handling { static void nesttry(int a) try if ( a == 1) a = a / (a - a); //division by zero if(a == 2) int c[] = {1}; c[42] = 99; //generate an out - of - bounds exception } catch(ArrayIndexOutOfBoundsException e) System.out.println("Array index out - of - bounds: " + e);
public static void main(String args[]) { try int a = args.length; int b = 42 / a; //If no command - line args are present, the //following statement will generate a divide - by - zero exception System.out.println("a = " + a); // nested try bloack // If one command - line arg is used, then a divide - by - //zero exception will be generated by the following code. nesttry(a); // Calling Static Method } catch(ArithmeticException e) System.out.println("Divide by Zero: " + e);
throw You have only been catching exceptions that are thrown by the java run – time system. However, it is possible for your program to throw an exception explicitly. Using throw statement. Syntax: throw ThrowableInstance; Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable. Simple types, such as int or char, as well as non – Throwable classes, such as String and Object, cannot be used as exception. There are two ways you can obtain a Throwable object: using a parameter into a catch clause, or creating one with the new operator.
class Error_Handling { static void display() try throw new NullPointerException("Demo"); } catch(NullPointerException e) throw e; public static void main(String args[]) display(); System.out.println("Recaught : " + e);
throws If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception. You do this by including a throws clause in the method’s declaration. A throws clause list the types of exceptions that a method might throw. This is necessary for all exceptions, except those of type Error or RuntimeException, or any of their subclasses. All other exceptions that a method can throw must be declared in the throws clause. If they are not, a compile – time error will result. type method-name (parameter-list) throws exception-list { //body of method } Here, exception – list is comma – separated list of the exceptions that a method can throw
class Error_Handling { static void throwdemo() throws IllegalAccessException System.out.println("Inside throwdemo"); } public static void main(String args[]) try throwdemo(); catch(IllegalAccessException e) System.out.println("Caught " + e);
Using finally Statement Java supports another statement known as finally statement that can be used to handle an exception that is not caught by any of the previous catch statements. finally block can be used to handle any exception generated within a try block. It may be added immediately after the try block or after the last catch block. try { //statements } catch(Exception-Type-1 e) catch(Exception-Type-2 e) ----------- catch(Exception-Type-N e) finally ------------------- try { //statements } finally -------------------
class Error_Handling { static void procA() try System.out.println("Inside ProcA"); throw new RuntimeException("demo"); } finally System.out.println("ProcA's finally"); static void procB() System.out.println("inside ProcB"); //return; System.out.println("ProcB's finally");
static void procC() { try System.out.println("inside ProcC"); } finally System.out.println("ProcC's finally"); public static void main(String args[]) procA(); catch(Exception e) System.out.println("Exception Caught"); System.out.println("Procedure A is Wind up"); procB(); procC(); } }
Java’s Built – in Exceptions The standard package java.lang, Java defines several exception classes. A few have been used by the preceding examples. The most general of these exceptions are subclasses of the standard type RuntimeException. Since java.lang is implicitly imported into all java programs, most exceptions derived from RuntimeException are automatically available. Furthermore, they need not be included in any method’s throws list. In the language of Java, these are called unchecked exceptions because the compiler does not check to see if a method handles or throws these exceptions. The other exceptions defined by java.lang 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. These are called checked exceptions.
Java’s Unchecked RuntimeException Subclasses Meaning ArithmeticException Arithmetic error, such as divde – by – zero ArrayIndexOutOfBoundsException Array index is out – of – bounds. ArrayStoreException Assignment to an array element of an incompatible type. ClassCastException Invalid Cast. IllegalArgumentException Illegal argument used to invoke a method IllegalMonitoStateException Illegal Monitor Operation, such as waiting on an unlocked thread. IllegalStateException Environment or application is in incorrect state. IllegalThreadStateException Requested operation not compatible with current thread state. IndexOutOfBoundsException Some type of index is out – of – bounds NegativeArraySizeException Array Created with a negative size.
Exception Meaning NullPointerException Invalid use of a null reference. NumberFormatException Invalid conversion of a string to a numeric format. SecurityException Attempt to violate security StringIndexOutOfBounds Attempt to index outside the bounds of a string. UnsupportedOperationException An unsupported Operation was encountered.
Java’s Checked Exception Defined in java.lang Meaning ClassNotFoundException Class not found CloneNotSupportedException Attempt to clone an object that does not implement the cloneable interface. IllegalAccessException Access to a class is denied InstantiationException Attempt to create an object of an abstract class or interface InterruptedException One thread has been interrupted by another thread. NoSuchFieldException A requested field does not exist. NoSuchMethodException A requested method does not exist.
throw new Throwable_subclass; Throwing our own Exceptions There may be times when we would like to throw our own exceptions. We can do this by using the keyword throw as follows: throw new Throwable_subclass; Example: throw new ArithmeticException(); throw new NumberFormatException(); Note: Exception is subclass of Throwable and therefore MyException is a subclass of Throwable class. An object of a class that extends Throwable can be thrown and caught
import java.lang.Exception; class MyException extends Exception { MyException(String message) super(message); } class Exception_Handling public static void main(String args[]) int x = 5, y = 1000; try float z = (float) x / (float) y; if (z < 0.01) throw new MyException("Number is too small");
catch(MyException e) { System.out.println("Caught my exception"); System.out.println(e.getMessage()); } finally System.out.println("I am always here");
Using Exceptions Exception handling provides a powerful mechanism for controlling complex programs that have many dynamic run – time characteristics. It is important to think of try, throw and catch as clean ways to handle errors and unusual boundary conditions in your program’s logic. If you are like most programmers, then you probably are used to returning an error code when a method fails. When you are programming in Java, you should break this habit. When a method can fail, have it throw an exception. This is a cleaner way to handle failure modes. One last point: Java’s Exception – handling statements should not be considered a general mechanism for nonlocal branching. If you do so, it will only confuse your code and make it hard to maintain.