</>

Technology

Java Programs

Difficulty

Intermediate

Interview Question

Write a Java program to demonstrate exception handling with try-catch-finally and custom exceptions.

Answer

Exception Handling in Java

Basic try-catch-finally

Java
public class ExceptionHandling {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;  // ArithmeticException
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Caught: " + e.getMessage());
        } finally {
            System.out.println("Finally always runs");
        }
    }
}

Output

CODE
Caught: / by zero
Finally always runs

Multiple catch Blocks

Java
public class MultiCatch {
    public static void main(String[] args) {
        try {
            String str = null;
            int[] arr = { 1, 2, 3 };

            System.out.println(str.length());    // NullPointerException
            System.out.println(arr[10]);         // ArrayIndexOutOfBoundsException

        } catch (NullPointerException e) {
            System.out.println("Null pointer: " + e.getMessage());
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array index out of bounds: " + e.getMessage());
        } catch (Exception e) {
            System.out.println("General exception: " + e.getMessage());
        } finally {
            System.out.println("Cleanup done");
        }
    }
}

Custom Exception

Java
// Define custom exception
class ElementNotFoundException extends RuntimeException {
    public ElementNotFoundException(String message) {
        super(message);
    }
    public ElementNotFoundException(String message, Throwable cause) {
        super(message, cause);
    }
}

// Use custom exception
public class CustomExceptionDemo {

    public static void clickElement(String selector) {
        try {
            // Simulating element not found
            if (selector.isEmpty()) {
                throw new ElementNotFoundException(
                    "Element with selector '" + selector + "' not found on page");
            }
        } catch (ElementNotFoundException e) {
            System.out.println("Test failed: " + e.getMessage());
            throw e;  // re-throw to fail the test
        }
    }

    public static void main(String[] args) {
        try {
            clickElement("");  // will throw custom exception
        } catch (ElementNotFoundException e) {
            System.out.println("Caught custom exception: " + e.getMessage());
        }
    }
}

Exception Hierarchy

CODE
Throwable
  ├── Error (JVM errors — don't catch these)
  │     └── OutOfMemoryError, StackOverflowError
  └── Exception
        ├── Checked Exceptions (must handle or declare throws)
        │     └── IOException, SQLException, ClassNotFoundException
        └── RuntimeException (unchecked — optional to catch)
              └── NullPointerException, ArrayIndexOutOfBoundsException,
                  ArithmeticException, ClassCastException

Automation Testing Relevance

Java
// Graceful element interaction with exception handling
public void clickIfExists(By locator) {
    try {
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
        WebElement el = wait.until(
            ExpectedConditions.elementToBeClickable(locator));
        el.click();
    } catch (TimeoutException e) {
        System.out.println("Element not found, skipping click: " + locator);
        // Don't throw — element is optional
    } catch (StaleElementReferenceException e) {
        // Retry once on stale element
        driver.findElement(locator).click();
    }
}

Follow AutomateQA