CS61B Guide
Search…
Exceptions

Basics

An exception occurs when something unintended occurs and the interpreter must exit.
While this might sound like a bad thing, we can often throw our own exceptions to handle known errors or edge cases more gracefully.

Exceptions in Java

In Java, there are two types of exceptions: checked and unchecked.
Checked exceptions are handled during compile time, and are included in the method declaration. As an example:
1
public void openFile() throws IOException {
2
...
3
}
Copied!
  • All children that override this method must also throw the same exceptions.
Unchecked exceptions are not handled during compile time, and thus are thrown during runtime. All Error or RuntimeException types are unchecked; all other exceptions are checked. Some examples of unchecked exceptions are dividing by zero (ArithmeticException), or accessing an index that doesn't exist (IndexOutOfBoundsException).
Some of the more common Exception types in Java.

Creating Custom Exceptions

We can use the throw keyword to create exceptions with custom error messages as follows:
1
public void divide(int a, int b) {
2
if (b == 0) {
3
throw new Exception("Error Message");
4
} else {
5
return a / b;
6
}
7
}
Copied!
This is often used within a try catch block, as such:
1
public void divide2() {
2
int a = 0;
3
try {
4
return 10 / 0;
5
} catch(Exception e) {
6
System.out.println("oops!");
7
}
8
}
Copied!
An alternate to custom exceptions is to simply handle exception cases. For example, we can add a check to make sure a number is not zero before running a division operation.

Try/Catch/Finally Example

Let's check your understanding of exception handling!
1
static String tryCatchFinally() {
2
try {
3
System.out.println("trying");
4
throw new Exception();
5
} catch (Exception e) {
6
System.out.println("catching");
7
return "done catch";
8
} finally {
9
System.out.println("finally");
10
}
11
}
Copied!
Q1
Q1 Answer
What will be printed (and in what order) when tryCatchFinally() is run?
First, trying will be printed.
Since an Exception is thrown, the catch block will run next, so catching is printed next.
Since finally blocks always run regardless of result, finally is printed last.
Q2
Q2 Answer
Suppose the same code were run, but without the catch block. What would this code do?
1
static String tryFinally() {
2
try {
3
System.out.println("trying");
4
throw new Exception();
5
} finally {
6
System.out.println("finally");
7
}
8
}
Copied!
If the try block throws an uncaught Exception (i.e. if catch block does not exist or catch block does not handle the type of Exception that is thrown in the try block), Java halts execution of the try block, executes the finally block, then raises a runtime error. So, the following sequence would occur: 1. trying is printed. 2. finally is printed. 3. The program exits with a RuntimeException.