Presentation is loading. Please wait.

Presentation is loading. Please wait.

Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }

Similar presentations


Presentation on theme: "Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }"— Presentation transcript:

1 Handling Exceptions in java

2 Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }

3 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

4 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”); double fact; for (fact=1.0; x>1; fact*=x, x--); return fact; }

5 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

6 Exception Handlers to detect and handle exceptions use try { … } catch (SomeException e1) { … } finally{ … } can have >1 catch blocks 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

7 Exceptions All exceptions have data - a String field that stores an error msg set when the exception is created e.g. accessed by a getMessage() method e.g. in the method that invokes the factorial() method if (x =0”); catch (IllegalArgumentException e){ System.out.println(“Error: + ”e.getMessage()); }

8 Checked/Unchecked Unchecked exceptions can be thrown at any time by virtually any method –e.g OutOfMemoryError, NullPointerException Checked exceptions occur in specific, well- defined circumstances –Well written applications should anticipate and cater for these –e.g.FileNotFoundException, EOFException IllegalArgumentException

9 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);... }

10 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); } }

11 User Defined Exceptions When your error occurs Handle your exception throw new MyException(); throw new MyException(“error specific string”); catch (MyException e){... }

12 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 ; }..

13 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; }

14 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.

15 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?

16 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; } }


Download ppt "Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }"

Similar presentations


Ads by Google