Sub topic 2
Running Code No Matter What: finally
The finally Block
A finally block is code that runs after a try block, whether the try block succeeded or failed. You use it for cleanup work that must always happen.
public class FinallyDemo {
static int divide(int a, int b) {
try {
return a / b;
} catch (ArithmeticException e) {
System.out.println("Failed: " + e);
return 0;
} finally {
System.out.println("finally always runs");
}
}
public static void main(String[] args) {
System.out.println(divide(10, 2));
System.out.println(divide(10, 0));
}
}Both calls print "finally always runs". The finally block runs even when the try block uses return.
Throwing and Declaring Exceptions
The throw keyword starts an exception yourself. The throws clause is part of a method's signature. It warns callers that the method may throw a checked exception.
Writing Your Own Exception Classes
A custom exception is a class you write that extends Exception (checked) or RuntimeException (unchecked). Its name says exactly what went wrong.
public class BankDemo {
static class InsufficientFundsException extends Exception {
InsufficientFundsException(String message) {
super(message);
}
}
static long balance = 50;
static void withdraw(long amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException("balance " + balance + " is less than " + amount);
}
balance -= amount;
}
public static void main(String[] args) {
try {
withdraw(100);
} catch (InsufficientFundsException e) {
System.out.println("Error: " + e.getMessage());
}
}
}Wrapping Exceptions and Preserving the Cause
Sometimes you catch a low-level exception and throw a clearer one. Pass the original exception as the cause, which is the earlier exception that led to this one. That way the details are not lost.
public class WrapDemo {
static long parseAmount(String text) {
try {
return Long.parseLong(text);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("bad amount: " + text, e);
}
}
public static void main(String[] args) {
try {
parseAmount("ten");
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage() + " / cause: " + e.getCause());
}
}
}Reading a Stack Trace
A stack trace is the report Java prints when nobody catches an exception. It lists the methods that were running, with the newest call at the top.
public class TraceDemo {
static int divide(int a, int b) {
return a / b;
}
public static void main(String[] args) {
System.out.println(divide(1, 0));
}
}Exception in thread "main" java.lang.ArithmeticException: / by zero
at TraceDemo.divide(TraceDemo.java:3)
at TraceDemo.main(TraceDemo.java:6)To find the cause, read the first line for the exception type, then the top at line for the file and line number. If an exception was wrapped, look for a "Caused by:" section further down.
Why Closing Resources Is Hard
A resource is something like an open file that you must close when you finish. If you forget to close it, the program can run out of file handles. The safe way to do this by hand uses finally:
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class ManualClose {
static String firstLine(Path path) throws IOException {
BufferedReader reader = null;
try {
reader = Files.newBufferedReader(path);
return reader.readLine();
} finally {
if (reader != null) {
reader.close();
}
}
}
}This version is long and easy to get wrong. If close() throws, its exception replaces the original one. The next chapter fixes both problems.
Exercise
In TraceDemo, which line of the stack trace tells you where the exception actually happened, and why?
Show answer
The top "at" line, TraceDemo.divide(TraceDemo.java:3), because the newest method call is listed first and that is where the division by zero ran.