Presentation is loading. Please wait.

Presentation is loading. Please wait.

Exception Handling in Java

Similar presentations


Presentation on theme: "Exception Handling in Java"— Presentation transcript:

1 Exception Handling in Java

2 Exceptions Something extra-ordinary is happening
An unexpected condition exists Exceptions are dealt with by an exception handler try/catch blocks Exceptions are not CRASHES The virtual machine exits normally. All memory is cleaned up. All resources are released.

3 Handling Exceptions Forces error checking
Cleans up your code by separating the normal case from the exceptional case. (The code isn't littered with a lot of if-else blocks checking return values.) Low overhead for non-exceptional case

4 Exception Types Exceptions are OBJECTS
All are derived from java.lang.Throwable The throwable provides a string that can be used as a detailed message

5 Class Throwable Provides some common methods String getMessage()
Void printStackTrace() Prints the sequence of the runtime stack when exception was thrown String toString()

6 Partial inheritance Class exception Class RunTimeException Class Error

7 Checked and unchecked exceptions
All exceptions are checked except RuntimeExceptions, Errors and their subclasses The compiler checks to see if an exception can be thrown and if so, it must be explicitly dealt with in a try/catch block

8 Try Catch Finally Try{ doSomething(a,b); }catch(Exception e){
e.printStackTrace(); }finally { cleanUpA(); cleanUpB(); }

9 Throw A program/ method can explicitly throw an exception. To signal a condition Throw new myNewException(“Problem”); Throw new ArithmeticException(“Int divide by 0”)

10 Throws Is used when a method can throw and exception
myNewMethod() throws MyNewException, MyOtherException

11 What to do with them Fix the problem and try again.
Do something else instead. Exit the application with System.exit() Rethrow the exception. Throw a new exception. Return a default value (in a non-void method). Eat the exception and return from the method (in a void method). Printing an error message by itself is generally not an acceptable response to an exception.


Download ppt "Exception Handling in Java"

Similar presentations


Ads by Google