Learn about exception handling and error management in Java to create more robust and fault-tolerant applications.
Exception handling is a crucial part of Java programming that allows developers to manage errors and unexpected situations gracefully.
Exceptions are events that disrupt the normal flow of program execution. They are objects that inherit from the java.lang.Throwable
class.
The Java exception hierarchy:
Use the throw
keyword to throw an exception when invalid inputs or states are detected.
public void deposit(double amount) { if (amount <= 0) { throw new IllegalArgumentException("Deposit amount must be positive"); } this.balance += amount; }
A NullPointerException
is thrown automatically by the JVM when a program attempts to use a null reference where an object is required.
String name = null; // This will throw a NullPointerException int length = name.length(); // Prevent NullPointerException with a null check if (name != null) { int length = name.length(); }
Use try-catch blocks to handle exceptions and finally blocks to ensure cleanup code always executes.
public void readFile(String filename) { FileReader reader = null; try { reader = new FileReader(filename); // Process file contents } catch (FileNotFoundException e) { System.err.println("File not found: " + filename); } catch (IOException e) { System.err.println("Error reading file: " + e.getMessage()); } finally { // This block always executes if (reader != null) { try { reader.close(); } catch (IOException e) { System.err.println("Error closing file"); } } } }
Create custom exception classes to provide more specific information about errors in your application.
// Custom exception class public class InsufficientFundsException extends Exception { private double amount; public InsufficientFundsException(double amount) { super("Insufficient funds: Needed $" + amount + " more"); this.amount = amount; } public double getAmount() { return amount; } } // Using the custom exception public void withdraw(double amount) throws InsufficientFundsException { if (amount > balance) { throw new InsufficientFundsException(amount - balance); } balance -= amount; }