Exception Handling
Type of Errors
- Syntax error
- Identified by compiler
- Logical error
- Identified by debugging
- Runtime error
- Bad inputs
- Unavailable resources
- Etc.
Exception Class
Methods
String getMessage()String toString()void printStackTrace()- Prints this throwable and its backtrace to the standard error stream
Error
Error cause the program to exit since they are not recoverable
Considered as unchecked exceptions
Checked exceptions: you must handle them at compile time
RuntimeExceptionUnchecked exceptions: you don't have to handle them
They’re always thrown automatically by Java and you don’t need to include them in your exception specifications
If a
RuntimeExceptiongets all the way out tomain( )without being caught,printStackTrace( )is called for that exception as the program exits; the output is reported toSystem.errCreating your own exceptions
class MinBalanceException extends Exception { public String toString() { return "Minimal balance should be 5000. Try again!" } }
How to Handle Exceptions
try { // logic that might generate exceptions } catch () { // handling exception if it occurs } finally { // activities happen every time even if a method is returned (executed before return) // cleanup }There can be zero, one, or multiple
catchblockstry catchblock can be nestedfinallyblock is necessary when you need to set something other than memory (garbage collector is responsible for releasing heap memories) back to its original state (releasing resources)
Objects in heap are also resources, the real composition of the program are the references on stack
The finally block will not be executed if program exits (either by calling
System.exit()or by causing a fatal error that causes the process to abort)Try with resources
Java 7 feature
Support multiple resources, separated by
;try (Scanner scanner = new Scanner(new File("test.txt"))) { while (scanner.hasNext()) { System.out.println(scanner.nextLine()); } } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } // no finally block // For objects which implement AutoClosable interface
Java supports termination exception handling instead of resumption
Throwing an exception
throw new Exception("");- Exceptions can be rethrown
- Happen in the
catchblock - Exception chaining: Often you want to catch one exception and throw another, but still keep the information about the originating exception
- Happen in the
- Exception propagation
- Exception bubbles up through the call stack if it is not caught
There is a pitfall in Java Exception implementation: lost exception
returninsidefinallyblock
Exception Specification
- Politely tell the client programmer what exceptions the method throws, so the client programmer can handle them
throws- Unchecked exceptions can be omitted
- The "exception specification interface" for a particular method may narrow during inheritance and overriding, but it may not widen
