Exceptions and week 7 review
Real programs fail: the user types letters where you expect a number, a file does not exist, the network goes down. An exception is an object that represents a problem that occurred during execution. If nobody handles it, the program ends with an ugly message, as you saw in week 1. With try and catch you can intercept the problem, react gracefully (show a warning, retry, use a default value) and go on. Handling errors well is what separates an example program from a reliable one.
try, catch and finally
The code that may fail goes inside try. If it throws an exception, execution jumps to the catch block whose type matches, and the program continues afterwards. You can put several catch blocks, from the most specific type to the most general, or group several types with a vertical bar. The finally block always runs, whether or not there was an exception, and serves to release resources. All exceptions inherit from Throwable; the ones you must handle are those that extend Exception. Avoid catching Exception indiscriminately and, above all, do not leave an empty catch: hiding an error is worse than letting it happen.
import java.util.List;
public class Main {
static int parseAge(String text) {
try {
int age = Integer.parseInt(text.trim());
if (age < 0) throw new IllegalArgumentException("age cannot be negative");
return age;
} catch (NumberFormatException e) {
System.out.println("Not a number: '" + text + "'");
return -1;
} finally {
System.out.println("checked: " + text); // always runs
}
}
public static void main(String[] args) {
System.out.println(parseAge("25"));
System.out.println(parseAge("abc"));
try {
parseAge("-3");
} catch (IllegalArgumentException e) {
System.out.println("Invalid: " + e.getMessage());
}
try {
String s = null;
System.out.println(s.length());
} catch (NullPointerException | ArithmeticException e) { // multi-catch
System.out.println("Caught " + e.getClass().getSimpleName());
}
try {
List.of(1, 2, 3).get(5);
} catch (IndexOutOfBoundsException e) {
System.out.println(e.getMessage()); // Index 5 out of bounds for length 3
}
}
}Custom exceptions, throws and resources
There are two families. Unchecked exceptions, which extend RuntimeException, indicate programming errors (NullPointerException, IllegalArgumentException) and do not force anything. Checked ones, such as IOException, represent environment failures that the compiler forces you to handle with try/catch or to declare with throws in the method signature, which passes the responsibility to the caller. You can create your own exceptions by extending Exception or RuntimeException, with a name that explains the problem, such as InsufficientFundsException. For resources that must be closed (files, connections) use try-with-resources: Java calls close() for you, even if there is an error.
public class Main {
// Custom checked exception
static class InsufficientFundsException extends Exception {
private final double missing;
InsufficientFundsException(double missing) {
super("Missing " + missing);
this.missing = missing;
}
double getMissing() { return missing; }
}
static class Wallet {
private double money;
Wallet(double money) { this.money = money; }
// throws: callers must handle or declare it
void pay(double amount) throws InsufficientFundsException {
if (amount > money) throw new InsufficientFundsException(amount - money);
money -= amount;
}
}
// A resource that closes itself
static class Connection implements AutoCloseable {
Connection() { System.out.println("open"); }
void send(String data) {
if (data.isEmpty()) throw new IllegalStateException("empty data");
System.out.println("sent " + data);
}
@Override public void close() { System.out.println("close"); }
}
public static void main(String[] args) {
Wallet wallet = new Wallet(20);
try {
wallet.pay(5);
wallet.pay(30);
} catch (InsufficientFundsException e) {
System.out.println(e.getMessage() + " (" + e.getMissing() + ")");
}
try (Connection c = new Connection()) {
c.send("hello");
c.send(""); // fails, but close() still runs
} catch (IllegalStateException e) {
System.out.println("Error: " + e.getMessage());
}
}
}Week 7 review
- Inheritance with extends and super; @Override to override; polymorphism: the version that runs depends on the real object.
- Abstract classes (state and common code) and interfaces (contracts, several at once, default methods).
- instanceof with a pattern to check and convert in one step; sealed and records for closed hierarchies.
- try / catch / finally; from the most specific to the most general; never an empty catch.
- Checked (require handling or throws) versus unchecked (RuntimeException); custom exceptions; try-with-resources.
Teste dein Wissen
Frage 1 von 6When does the finally block run?
✎ Meine Notizen
Nur in diesem Browser gespeichert. Melde dich an, um es im Konto zu behalten.0/5000 Zeichen