Exceptions

Embed Size (px)

DESCRIPTION

JAVA Exceptions

Citation preview

  • Exception Handling

    An Exception is an abnormal condition that arises in a code sequence at run time.

    A Java Exception is an object that describes an exceptional condition that has occurred.

    Exceptions can be generated by the Java-Runtime system or your code.

  • class Example {public static void main(String args[]) {int d = 0;int a = 42 /d;System.out.println("a = " + a);}}

  • Exception Handling Syntax:try {// Code that might generate exceptions} catch(Type1 id1) {// Handle exceptions of Type1} catch(Type2 id2) {// Handle exceptions of Type2} // etc...finally {// Stuff that happens every time }

  • Java programs have the following advantages over traditional error management techniques: 1: Separating Error Handling Code from "Regular" Code 2: Propagating Errors Up the Call Stack 3: Grouping Error Types and Error Differentiation

  • Advantage 1: Separating Error Handling Code from "Regular" CodeIn traditional programming, error detection, reporting, and handling often lead to confusing code.

    In pseudo-code, a function that reads an entire file might look something like this: readFile { open the file; determine its size; allocate that much memory; read the file into memory; close the file; }

  • At first glance this function seems simple enough, but it ignores all of these potential errorsWhat happens if the file can't be opened? What happens if the length of the file can't be determined? What happens if enough memory can't be allocated? What happens if the read fails? What happens if the file can't be closed?

    To answer these questions within your read_file function, you'd have to add a lot of code to do error detection,reporting and handling.

  • Your function would end up looking something like this: errorCodeType readFile { initialize errorCode = 0; open the file; if (theFileIsOpen) { determine the length of the file; if (gotTheFileLength) { allocate that much memory; if (gotEnoughMemory) { read the file into memory; if (readFailed) { errorCode = -1; } } else { errorCode = -2; } } else { errorCode = -3; } close the file; if (theFileDidntClose && errorCode == 0) { errorCode = -4; } else { errorCode = errorCode and -4; } } else ..

  • In Java the same code will look like:readFile { try { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } catch (fileOpenFailed) { doSomething; } catch (sizeDeterminationFailed) { doSomething; } catch (memoryAllocationFailed) { doSomething; } catch (readFailed) { doSomething; } catch (fileCloseFailed) { doSomething; } } Actual code Exceptioncode

  • Advantage 2: Propagating Errors Up the Call StackThe Java runtime system searches backwards through the call stack to find any methods that are interested in handling a particular exception. A Java method can "duck" any exceptions thrown within it, thereby allowing a method further up the call stack to catch it. method1 { try { call method2; } catch (exception) { doErrorProcessing; } } method2 throws exception { call method3; } method3 throws exception { call readFile; }

  • Advantage 3: Grouping Exception Types Often exceptions fall into categories or groups.

    Because all exceptions that are thrown within a Java program are objects, grouping or categorization of exceptions is a natural outcome of the class hierarchy.

  • ExceptionThrowableErrorEOFExceptionInterruptedExceptionIOExceptionRuntimeExceptionNullPointerExceptionIndexOutOfBoundsExceptionNegativeArraySizeException ArrayIndexOutOfBoundsExceptionFileNotFoundExceptionArithmeticExceptionStringIndexOutOfBoundsExceptionUnsatisfiedLinkerErrorStackOverFlowError

  • Runtime exceptions represent problems that are detected by the runtime system. This includes arithmetic exceptions (such as when dividing by zero), pointer exceptions (such as trying to access an object through a null reference), and indexing exceptions (such as attempting to access an array element through an index that is too large or too small). Runtime exceptions can occur anywhere in a program and in a typical program can be very numerous. Typically, the cost of checking for runtime exceptions exceeds the benefit of catching or specifying them. Thus the compiler does not require that you catch or specify runtime exceptions, although you can. Checked exceptions represent useful information about the operation of a legally specified request that the caller may have had no control over and that the caller needs to be informed about--for example, the file system is now full, or the remote end has closed the connection.

  • Examples

  • class EX{public static void main(String args[]){ int d ,a;try {//monitor a block of coded = 0; a = 42 /d; System.out.println(This will not be printed); } catch(ArithmeticException e){System.out.println(Division by Zero);} System.out.println(After Catch);}

  • public static void main(String args[]){int x=4,y=2,z=0;try {z=x/y; System.out.println("Does not Execute"); }catch(ArithmeticException e){z=0;System.out.println(e);}finally{System.out.println("X= " +x +"Y=" +y+"Z="+z);}}/* finally block is executed if exception is thrown or not */

  • public static void main(String args[]){int k=0;for(int i=0;i
  • int k=0;for(int i=0;i
  • Example for Exceptions are pushed up the Call Stackpublic static void method(){int k=0;for(int i=0;i
  • public static void main(String args[]){try{method();}catch(Exception e){System.out.println("Any type of exception" +e);}}

  • Throwing your own Exceptionclass Ex{public static void Ticket(int a) throws Exception{if(a>60) throw new Exception("Too old ");else if(a
  • Creating Your own Exception Subclasses Define a subclass of Exception Override String toString( ) method, allowing the description of the exception to be displayed using println()

  • class AgeException extends Exception{int age;String msg;AgeException(String m,int a){msg=m;age=a;}public String toString(){return "You are " +age + " and " +msg;}}

  • class Ex{public static void Ticket(int a) throws AgeException{if(a>60) throw new AgeException("Too old ",a);else if(a
  • java.util packageJava Collection FrameworkInterfacesImplemetation classesUtility classes