Exceptions and Errors
> Click or hit Control-Enter to run the code above
Exceptions
Because things go wrong…
Why Exceptions?
What do you do when you can’t go on?
class StringStorage {
/**
* Create a new object to store strings.
*
* @param storageSize the size of the StringStorage,
* must be positive
*/
public StringStorage(final int storageSize) {
if (storageSize <= 0) {
// what now?
}
}
}
Why Exceptions?
What do you do when you can’t go on?
/**
* Read an integer from a passed string
* and then do something with it.
*/
static int readInteger(final String intAsString) {
int value = Integer.parseInt(intAsString);
// But what if intAsString was "foo"?
}
try-catch
Java’s exception handling control structure is called a try-catch
block:
try {
// Do something that could cause an exception
} catch (Exception e) {
// Handle all exceptions that inherit from Exception
}
// Go on if things proceeded normally
catch
Matching
A catch
block will match any exceptions that inherit from the one provided.
And they are tried in order.
try-catch
with Multiple catch
Sometimes you want to handle errors differently depending on what caused them:
try {
// Do something that could cause an exception
} catch (NullPointerException e) {
// Handle null pointer exceptions
} catch (ArrayIndexOutOfBoundsException e) {
// Handle array out of bounds exceptions
}
// Go on if things proceeded normally
try-catch
with Multiple catch
You can also merge multiple exception types together like this:
try {
// Do something that could cause an exception
} catch (NullPointerException|IllegalArgumentException e) {
// Handle null pointer and illegal argument exceptions
}
// Go on if things proceeded normally
try-catch
in Python
Many other languages have similar error handling constructs. In Python:
try:
// do something
except ValueError:
// handle
except Another Error:
// handle
else:
// Run if no error is thrown. No analog in Java
finally:
// Always run
try-catch
in JavaScript
Many other languages have similar error handling constructs. In JavaScript:
try {
// do something
} catch (err) {
// handle the err
} finally {
// Always run
}
> Click or hit Control-Enter to run the code above
Exceptional Control Flow
When an error is thrown control flow immediately jumps to an
enclosing catch
statement, if one exists.
The catch
may be in the caller or multiple levels up.
static void foo1() {
Object it = null;
int hash = it.hashCode();
}
static void foo2() {
foo1();
}
static void foo3() {
foo2();
}
static void foo4() {
try {
foo3();
} catch (Exception e) {
}
}
> Click or hit Control-Enter to run the code above
Types of Exceptions
Java exceptions are broken into three distinct categories:
-
Checked exceptions: these are for places where you know something might go wrong and it’s out of your control
-
Unchecked exceptions (or runtime errors): these are unanticipated errors usually caused by something dumb that you (the programmer) did wrong
-
Errors: these are reserved for serious system problems that are probably not recoverable
Checked Exceptions: Examples
Checked exceptions are for cases where an failure external to your program can cause an exception to occur
-
FileNotFoundException
: your program tried to open a file that you expected to exist but it did not -
URISyntaxException
: your program tried to parse a universal resource identifier (URI) but it was invalid
Checked Exceptions: Handling
If you use a function that may generate a checked exception, you must either
wrap it in a try-catch
block or declare that you may throw it.
static URI createURI(final String input) {
// Example where we handle URISyntaxExceptions
try {
return new URI(input);
} catch (URISyntaxException e) {
System.out.println(input + " is not a valid URI");
}
}
// Example where we throw URISyntaxExceptions
static URI createURI(final String input) throws URISyntaxException {
return new URI(input);
}
> Click or hit Control-Enter to run the code above
Unchecked Exceptions
Unchecked examples are usually the result of programmer error.
(They are fundamentally unanticipated, since if you had anticipated them you would have fixed them.)
You’ve probably made many of these mistakes by now…
-
ArrayIndexOutOfBoundsException
: you walked off the end of an array -
NullPointerException
: you dereferenced anull
reference -
ClassCastException
: you tried to cast something to a subclass of which it is not an instance -
IllegalArgumentException
: you passed incorrect arguments to a function or constructor
> Click or hit Control-Enter to run the code above
Unchecked Exceptions: Handling
Unlike checked exceptions, you do not need to declare or handle unchecked exceptions.
However, you can handle them:
try {
String s = callMyPartnersDodgyCode();
if (s.length() == 0) {
return;
}
} catch (NullPointerException e) {
return;
}
Errors: Examples
Java errors indicate serious conditions that are usually not recoverable:
-
OutOfMemoryError
: Java ran out of memory and is going to crash -
StackOverflowError
: You recursed too deeply and Java is going to crash -
Note that sometimes these are still your fault: you used too much memory or forgot your base case
Exception Handling Strategies
Here are reasonable strategies for handling each kind of exception:
-
Errors: don’t try to handle these, just go bye-bye
-
Unchecked exceptions: try to avoid these by improving your code
-
Checked exceptions: try to handle these and have your program continue running, or exit gracefully…
-
but don’t go on unless you can.
Announcements
-
The final project description has been posted. Please get started!
-
I have office hours MWF from 10AM–12PM in Siebel 2227. Please stop by!
-
Remember to provide feedback on the course using the anonymous feedback form.
-
I’ve started to respond to existing feedback on the forum.