Exceptions and Errors
> Click or hit Control-Enter to run the code above
> Click or hit Control-Enter to run Example.main 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 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: Examples
Unchecked examples are usually the result of programmer error.
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
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;
}
Final Project Reminders
You have less than two weeks to complete your final project!
-
You need a partner. You’re about to lose 20 points if you don’t have one.
-
You need a UI. See above.
-
Have fun!
-
Questions?
ICES Plan and Incentives
The way that we do ICES is really dumb…
-
We’ll be doing our own custom end-of-semester survey, so you’ll have a chance to fill out an evaluation online like a normal human being.
-
(And we’ll get the feedback before the class is offered multiple more times.)
ICES Plan and Incentives
…but I still want you to complete the ICES forms. So to incentivize participation:
-
If you get to 70% I’ll release one of the short programming problems from the exam
-
If you get to 80% I’ll release another programming problem from the exam
-
If you get to 90% I’ll release a hard programming problem from the exam
-
Note that the TAs will be supervising the ICES forms so that I can trust the count. And the 8AM and 10AM classes are in this together.
Announcements
-
MP7 (the final project) is out. Please get started!
-
The anonymous feedback form remains available on the course website. Use it to give us feedback!
-
My office hours continue today at 11AM in the lounge outside of Siebel 0226.