Java:Java Exception Handling: try, catch, finally, and throws
Java•Error Handling

Java Exception Handling: try, catch, finally, and throws

Learn the difference between checked exceptions (IOException) and unchecked runtime exceptions (NullPointerException).

Syntax

try { // risky code } catch (Exception e) { // handle } finally { // cleanup }

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
try-catchBlockMonitors block for exceptions and routes to handler.
finallyBlockExecutes unconditionally for resource release.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Java locally:

public class Main {
    public static double divide(double a, double b) throws ArithmeticException {
        if (b == 0) {
            throw new ArithmeticException("Division by zero error.");
        }
        return a / b;
    }

    public static void main(String[] args) {
        System.out.println("Starting computation:");
        try {
            System.out.println("Result: " + divide(100, 4));
            System.out.println("Result: " + divide(50, 0));
        } catch (ArithmeticException e) {
            System.out.println("[CAUGHT] Arithmetic Error: " + e.getMessage());
        } finally {
            System.out.println("[CLEANUP] Routine complete.");
        }
    }
}
Expected Output:
Starting computation:
Result: 25.0
[CAUGHT] Arithmetic Error: Division by zero error.
[CLEANUP] Routine complete.

How It Works: Step-by-Step

  • Lines 2-7: divide method throws ArithmeticException when denominator is zero.
  • Lines 11-18: try block catches ArithmeticException and executes finally cleanup.

Key Concepts

  • Checked exceptions must be caught or declared in the method signature with throws.
  • Unchecked exceptions (subclasses of RuntimeException) do not require explicit throws declarations.
  • finally blocks execute even if a return statement is encountered in try or catch.

Common Mistake: Catching generic Exception before specific subclass exceptions

catch(Exception e) catches everything, making subsequent specific catch blocks unreachable.

❌ Incorrect
catch (Exception e) {}
catch (IOException e) {} // Compile Error: unreachable code
✅ Correct
catch (IOException e) {}
catch (Exception e) {}

Related Java Tutorials & Compiler

Run and test Java on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Java Online Compiler