Back to the 2023 paper

Module III: Basics of Web Programming

20237m

Explain the concept of Exception Handling. How will you create your own exception?

Worked SolutionAI Assisted

Exception handling

An exception is an abnormal event during execution (divide by zero, invalid input, missing file) that disrupts the normal flow. Exception handling is the mechanism to detect and handle such events gracefully so the program does not crash.

Keywords in Java: try, catch, finally, throw, throws.

try {
    int r = 10 / 0;                      // risky code
} catch (ArithmeticException e) {         // handler
    System.out.println("Error: " + e.getMessage());
} finally {
    System.out.println("Always runs");   // cleanup
}
  • try: contains code that may throw.
  • catch: handles a specific exception type (multiple catch blocks allowed).
  • finally: runs whether or not an exception occurred (close files, connections).
  • throw: explicitly throws an exception object.
  • throws: declares that a method may throw a checked exception.

Types: checked (checked at compile time, e.g. IOException), unchecked (runtime, e.g. NullPointerException), and errors (e.g. OutOfMemoryError).

Creating your own (user-defined) exception

Extend Exception (checked) or RuntimeException (unchecked), then throw it where the condition occurs.

class InvalidAgeException extends Exception {
    InvalidAgeException(String message) {
        super(message);
    }
}

class Demo {
    static void validate(int age) throws InvalidAgeException {
        if (age < 18)
            throw new InvalidAgeException("Age must be at least 18");
        System.out.println("Valid age");
    }

    public static void main(String[] args) {
        try {
            validate(15);
        } catch (InvalidAgeException e) {
            System.out.println("Caught: " + e.getMessage());
        }
    }
}

Output: Caught: Age must be at least 18

Steps: (1) create a class extending Exception, (2) add a constructor that passes the message to super, (3) throw it with throw new ..., (4) declare it with throws if checked, (5) catch it with try/catch.

JavaScript equivalent:

class InvalidAgeError extends Error {
  constructor(msg) { super(msg); this.name = 'InvalidAgeError'; }
}
try { throw new InvalidAgeError('Age must be at least 18'); }
catch (e) { console.log(e.name + ': ' + e.message); }

Similar questions

Budget AppAndroid App

Pocketly on Android

Log daily food, travel, and hostel expenses instantly. Set monthly spending limits and see where your money goes without complex spreadsheets.