Lesson 16 of 20

Exception Handling

Exception Handling

Java uses exceptions to handle errors at runtime. When something goes wrong, an exception is thrown, and you can catch it to handle it gracefully.

try / catch / finally

try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Error: " + e.getMessage());
} finally {
    System.out.println("This always runs");
}
  • try — wraps code that might throw an exception
  • catch — handles a specific exception type
  • finally — always executes, whether an exception occurred or not (useful for cleanup)

Checked vs Unchecked Exceptions

  • Unchecked (RuntimeException and its subclasses): NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException. The compiler does not force you to handle these.
  • Checked (Exception but not RuntimeException): IOException, SQLException. The compiler forces you to either catch them or declare them with throws.

Throwing Exceptions

Use throw to raise an exception yourself:

void setAge(int age) {
    if (age < 0) {
        throw new IllegalArgumentException("Age cannot be negative");
    }
}

Custom Exceptions

You can define your own exception classes by extending Exception (checked) or RuntimeException (unchecked):

class InsufficientFundsException extends RuntimeException {
    private double deficit;

    InsufficientFundsException(double deficit) {
        super("Insufficient funds: need " + deficit + " more");
        this.deficit = deficit;
    }

    double getDeficit() { return deficit; }
}

Your Task

Create a static inner class SafeCalculator with:

  • static String divide(int a, int b) — returns the result as a string, or "Error: division by zero" if b is 0 (use try/catch on ArithmeticException)
  • static String parseAndAdd(String x, String y) — parses both strings as integers and returns their sum as a string. If either string is not a valid integer, return "Error: invalid number". Use a finally block to print "parse complete" regardless of outcome.

Also create a custom exception class NegativeNumberException (extending RuntimeException) with a constructor that takes a String message, and a method:

  • static int squareRoot(int n) — if n < 0, throw NegativeNumberException with message "negative input: " followed by n. Otherwise return (int) Math.sqrt(n).

Then run the test sequence shown in the expected output.

TeaVM (WASM) loading...
Loading...
Click "Run" to execute your code.