Exceptions
Try ... catch ... finally
try {...}
catch (MyException e) {...}
catch (AnotherException e) {...}
finally {...}
- Catch blocks in the same function in which the exception was thrown will not be executed.
- Finally blocks are useful for cleanup code that must always be executed.
- Finally blocks always execute after the flow-of-control leaves the try block, whether by continue, break, return, throw, or finishing the try block.
Throw
- Any object that implements the Throwable interface can be thrown; however, generally only throw objects derived from class Exception.
if (x != 4)
throw new MyException();
Throws
double MyMethod()
throws ExceptionName [, ExceptionName]*
{...}
- Declares the exceptions that a method may throw.
- If a method might throw an exception, or doesn't handle one it might receive, the method must declare the exception.
Common exceptions
- ArithmeticException
- ArrayIndexOutOfBoundsException
- ClassCastException
- InterruptedException
- IOException
- NullPointerException
- OutOfMemoryException
Debugging
e.getMessage(); // Returns a descriptive string.
e.toString(); // Displays the exception type.
e.printStackTrace(); // Shows where the exception occurred.
Resources URL:
notes/java/resources
Sources URL:
notes/java/sources