Exceptions and Errors Continued
> 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…
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: 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);
}
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
> 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.
Working with Exceptions
Java exceptions are just another kind of Java object—and they have some useful features, particularly when debugging:
-
toString
: like every other JavaObject
, exceptions can be printed -
getMessage
: retrieves just the message associated with this exception -
printStackTrace
: print a stack trace for the error showing what caused it and what other functions were involved
> Click or hit Control-Enter to run the code above
Rethrowing Exceptions
Sometimes you may want to just record what happened but not know what to do with an error.
In that case you may want to rethrow it out of the catch block:
static URI createURI(final String input) {
// Example where we handle URISyntaxExceptions
try {
return new URI(input);
} catch (URISyntaxException e) {
// Log that something went wrong
Log.e(TAG, input + " is not a valid URI");
// Rethrow the exception
throw(e);
}
}
Throwing Your Own Exceptions
So how do we handle a case like this?
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?
}
}
}
> Click or hit Control-Enter to run Example.main above
throw
To throw an exception in Java we use the throw
keyword:
Exception e = new Exception("you did something awful");
throw(e);
throw
Well
If you need to throw an exception:
-
Look for an existing
Exception
class that’s a good fit -
Or, create your own:
public class MyException extends Exception {
}
throw(new MyException("bad bad"));
finally
Java’s try-catch
also supports a finally
block. It is always executed after
either the try
or the catch
completes:
try {
System.out.println("start");
couldError();
System.out.println("done");
} catch (Exception e) {
System.out.println("catch");
} finally {
System.out.println("finally");
}
> Click or hit Control-Enter to run the code above
Intelligent try
Usage
You can make intelligent use of try-catch
blocks to avoid repetitive sanity
checking:
JsonParser parser = new JsonParser();
JsonObject info = parser.parse(json).getAsJsonObject();
if (!info.has("metadata")) {
return 0;
}
JsonObject metadata = info.getAsJsonObject("metadata");
if (!metadata.has("width")) {
return 0;
}
JsonElement width = metadata.getAsJsonElement("width");
return width.getAsInt();
Intelligent try
Usage
You can make intelligent use of try-catch
blocks to avoid repetitive sanity
checking:
(This is particularly nice when you can chain calls together.)
try {
JsonParser parser = new JsonParser();
return parser.parse(json)
.getAsJsonObject()
.getAsJsonObject("metadata")
.get("width")
.getAsInt();
} catch (Exception e) {
return 0;
}
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.