Exception Handling in Java
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.
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
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
Class Throwable Provides some common methods String getMessage() Void printStackTrace() Prints the sequence of the runtime stack when exception was thrown String toString()
Partial inheritance Class exception Class RunTimeException Class Error
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
Try Catch Finally Try{ doSomething(a,b); }catch(Exception e){ e.printStackTrace(); }finally { cleanUpA(); cleanUpB(); }
Throw A program/ method can explicitly throw an exception. To signal a condition Throw new myNewException(“Problem”); Throw new ArithmeticException(“Int divide by 0”)
Throws Is used when a method can throw and exception myNewMethod() throws MyNewException, MyOtherException
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.