Introduction to Java exceptions
A brief introduction toJava
exceptions
: what they are, the classes involved, whatjava.lang.Error
is, whereexceptions
come from (where they are generated), and whyexceptions
are useful.Useful resources
The video page on YouTube.
The video's slides.
An example of an
exception
thrown by an attempt to read a file that does not exist on the local file system. In the example we also see how theexception
provides a description of what failed.In this example we see that not handling a
checked
exception
causes a compile-time error; this does not happen withunchecked
exceptions
.An example of a
java.lang.Error
caused by a recursive function without a proper condition that ends the recursion: in this case aStackOverflowError
is generated indicating that the stack memory allocated by the JVM has run out.An example of a
java.lang.Error
caused by an iteration that adds objects to a list without a criterion that ends the iteration: in this case anOutOfMemoryError
is generated that indicates that the heap memory allocated by the JVM has run out.In this example we see how we can
throw
anexception
in our code to notify the caller of the current method that an error condition has occurred. This is done by thethrow
keywork.In this example we show a bad handling of an error condition. The bad handling is in not using
exceptions
, a decision that forces us to mix the business logic code with the code needed to handle the error condition.In this example we show a bad handling of an error condition. The bad handling is in not using