Java Cheat Sheet: Errors and Exception Handling

1. Try-Catch Block

try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero.");
}

2. Catching Multiple Exceptions

try {
    // some code
} catch (IOException | SQLException ex) {
    System.out.println("IO or SQL Exception occurred.");
}

3. Finally Block

try {
    // some code
} catch (Exception e) {
    System.out.println("Caught Exception");
} finally {
    System.out.println("Always executes");
}

4. Throwing Exceptions

public void checkAge(int age) {
    if (age < 18) {
        throw new IllegalArgumentException("Underage");
    }
}

5. Creating Custom Exceptions

class MyException extends Exception {
    public MyException(String message) {
        super(message);
    }
}

6. Checked vs Unchecked Exceptions

// Checked: must be declared or handled
public void readFile() throws IOException {
    FileReader fr = new FileReader("file.txt");
}

// Unchecked: runtime exceptions
int[] arr = new int[2];
System.out.println(arr[3]);  // ArrayIndexOutOfBoundsException

7. Common Exception Types

  • ArithmeticException
  • NullPointerException
  • ArrayIndexOutOfBoundsException
  • ClassNotFoundException
  • IOException
  • FileNotFoundException
  • IllegalArgumentException

8. Using throw and throws

public void validate(int age) throws IllegalArgumentException {
    if (age < 0) {
        throw new IllegalArgumentException("Negative age");
    }
}

9. Multi-Catch and Try-with-Resources

try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
    System.out.println(br.readLine());
} catch (IOException e) {
    e.printStackTrace();
}