160 likes | 295 Views
Handling Exceptions in java. Exception handling blocks. try { body-code } catch (exception-classname variable-name) { handler-code }. Exceptions. An exception is an event that occurs during the execution of a program that disrupts the normal flow
E N D
Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
Exceptions • An exception is an event that occurs during the execution of a program that disrupts the normal flow • a signal that some sort of exception condition or error has occurred • Exceptions must be detected and handled so the program can continue if at all possible • To throw an exception is to signal an exceptional condition • to catch an exception is to handle it • An exception is an object
throw • signals that some sort of exceptional condition or error has occurred • example, in class ArithmeticUtilities • public static double factorial(int x){ • if (x<0) throw new IllegalArgumentException( “x must be >=0”); • double fact; for (fact=1.0; x>1; fact*=x, x--); return fact;}
What happens exceptions… • When a throw statement is executed… • normal program execution stops • it searches for an exception handler to catch the exception • if the exception is caught (ie. handled) execution continues at the statement after the handler code • if the exception is not caught, the interpreter looks for a handler in the calling method and continues searching up the Java call stack • if the exception is never caught, the JRE prints an error msg, a stack trace and exits
block of code where an exception may occur, i.e. be thrown block(s) of code where one or more exceptions are handled block of code to clean up after the code in the try clause Exception Handlers • to detect and handle exceptions use try { … } catch (SomeException e1) { … } finally{ … } can have >1catch blocks
Exceptions • All exceptions have data - a String field that stores an error msg • set when the exception is createde.g. • accessed by a getMessage() methode.g. in the method that invokes the factorial() method • if (x<0) throw new IllegalArgumentException(“x must be >=0”); • catch (IllegalArgumentException e){ System.out.println(“Error: + ”e.getMessage());}
Checked/Unchecked • Unchecked exceptions can be thrown at any time by virtually any method • e.gOutOfMemoryError, NullPointerException • Checked exceptions occur in specific, well-defined circumstances • Well written applications should anticipate and cater for these • e.g.FileNotFoundException, EOFExceptionIllegalArgumentException
Checked Exceptions • If a method invokes another method that “throws” a checked exception it must either • include exception handling code to handle the exception • use throws in the method declaration to declare that this method also throws that exception • e.g. (though not necessarily a good idea!)a method that invokes factorial but does not handle the IllegalArgumentException • void myMethod() throws IllegalArgumentException { ... ArithmeticUtilities.factorial(5); ...}
User Defined Exceptions • To define a new exception, create a subclass of Exception • Include two constructors, • the default constructor • one to allow for an error specific message • class MyException extends Exception { • MyException(){ } • MyException(String s){ super(s); }}
User Defined Exceptions • When your error occurs • Handle your exception • throw new MyException(); • throw new MyException(“error specific string”); • catch (MyException e){ ...}
User defined exceptions public class InvalidAgeException extends Exception { private int age; public InvalidAgeException {}; public InvalidAgeException(int age) { this.age = age; } public String toString() { return "Age cannot be negative" + " " +age ; } ..
Using the user defined exception.. .. In another class.. if (age < 0){ throw new InvalidAgeException(age); }else{ System.out.println("Age entered is " + age); } } static int getAge() { return -10; } }
So remember.. • Try/ Catch/ Finally… blocks • The try{}Catch{} structure should be used when it is possible that your method/code will fail. • if you use a method for input that requires an int, and the user enters a double, it will fail, throwing an exception. Methods like that need to be in try/catch structures.
User Defined Exceptions • At first glance, this function seems simple enough, but it ignores all the following potential errors. • What 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?
User Defined Exceptions • 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; } • }