Exceptions and Next Steps
An exception is an error that happens while the program runs. Catch it with try / catch so the program does not crash. finally always runs.
Real programs meet problems they can't prevent: a file isn't there, the network is down, a user types "abc" where a number is expected. Java represents each problem as an exception object that is "thrown". If nothing catches it, the program stops and prints a stack trace (the list of method calls that led to the error) - very useful for finding bugs.
Catch exceptions where you can actually do something useful - show a friendly message, retry, or use a default. Catch the most specific type you expect (NumberFormatException), not a general Exception, so real bugs aren't hidden. You can also throw your own with throw new IllegalArgumentException("...") when a method gets bad input.
try-with-resources
Files and database connections must be closed. try-with-resources closes them for you automatically:
Anything that opens a resource - a file, a network connection, a database connection - must close it, or your program slowly leaks resources until it fails. Before Java 7 this needed a messy finally block; try-with-resources closes everything automatically, even if an exception happens.
import java.io.*;
try (BufferedReader r = new BufferedReader(new FileReader("orders.txt"))) {
System.out.println(r.readLine());
} catch (IOException e) {
System.out.println("Could not read the file");
}- Checked exceptions (like
IOException) must be caught or declared withthrows. - Unchecked exceptions (like
NullPointerException) usually mean a bug to fix.
What to learn next
- Concurrency: running tasks at the same time with
ExecutorService. - Files (NIO.2):
Files.readAllLines(.Paths.get("a.txt")) - JDBC: talking to a database.
- Build tools Maven or Gradle, and the Spring Boot framework.
- Exceptions are errors thrown while the program runs.
- Catch specific types with
try/catch;finallyalways runs. - try-with-resources closes files and connections automatically.
- Checked exceptions must be handled or declared; unchecked ones usually mean bugs.
