Code examples used for this class were from “Java How to Program” Ch. 13
Recommended Study Action:
Review the Self review exercises of Ch 13
Read all exercises of Ch. 13 and formulate ideas as to how these problems would be completed.
Try to implement 13.20, 13.21
What are exceptions?
Exceptions
are Objects that are created that describe an error condition that occurred in
a program
Exceptions
are Objects
The Exception Hierarchy
Recoverable Exceptions ( Class
Exception )
IOException
RuntimeException
Non-Recoverable Exceptions ( Class
Error )
OutOfMemoryError
ThreadDeath
AWTError
Checked Exceptions ( Class
IOException )
Usually a resource issue.
Compiler
checks to verify they are handled.
Unchecked Exceptions ( class
RuntimeException )
Usually due to poor coding practices.
Compiler
does not force handling.
OutOfBoundsException
ArithmeticException
Convention - Exceptions should end with the word 'Exception'
Exceptions handle synchronous errors not asynchronous events
How do we handle exceptions?
Try Block
Catch Block
Catch or Declare
A method
must catch or declare a checked exception
To declare
an exception use 'throws ...'
finally
Used to
clean up allocated resources and close files
Stack Unwinding
when an un-caught exception is thrown from a method,
the parent method is checked for a catch,
then its parent,
and so on... until a catch is found.
If no catch
is found the thread terminates.
Exception Stack trace
Stack
traces help determine where/why the exception was thrown?
Chained Exceptions
One
exception type occurs
A different
exception is thrown to better represent the error to the calling method
pre-condition
a condition the is assumed to be true before a method runs
post-condition
a condition that is supposed to be true after a method runs
assert
used for checking pre and post conditions.
Asserts are
not processed by default!
asserts throw AssertionError
Performance?
Use tests
if possible not exceptions!
The try
block creates overhead that can slow a program down significantly!
How to create new Exceptions:
public class MyException extends Exception {
public MyException() {}
public MyException( String detail ) {
super( detail );
}
}
You can declare non checked exceptions, but DONT!
Exceptions for constructors
When a
constructor throws an exception the object is not created!
Multiple Catch blocks
More
specific catches should be first!
You can not
catch the same item twice!
If you can't really handle the exception throw it again!