YourWalkOnTech

Enjoy your walk on technology

Introduction to Java exceptions

A brief introduction to

Java

exceptions

: what they are, the classes involved, what

java.lang.Error

is, where

exceptions

come from (where they are generated), and why

exceptions

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 the

exception

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 with

unchecked

exceptions

.                                                               
An example of a

java.lang.Error

caused by a recursive function without a proper condition that ends the recursion: in this case a

StackOverflowError

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 an

OutOfMemoryError

is generated that indicates that the heap memory allocated by the JVM has run out.       
In this example we see how we can

throw

an

exception

in our code to notify the caller of the current method that an error condition has occurred. This is done by the

throw

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

exceptions

, a decision that forces us to mix the business logic code with the code needed to handle the error condition.