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:
| Parameter | Type | Description |
|---|---|---|
| try-catch | Block | Monitors block for exceptions and routes to handler. |
| finally | Block | Executes unconditionally for resource release. |
Ready-to-Run Code Example
Executable in CompilraRun 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
Java Try-With-Resources and File I/O (AutoCloseable)
Ensure automatic resource closing using Java 7+ try-with-resources statement.
Java Classes and Object-Oriented Programming (OOP)
Construct blueprints with constructors, private fields, getters, and setters.
Java Methods: Static Methods, Return Values, and Overloading
Learn how to declare methods, pass arguments, return values, and overload method signatures.
Java Online Compiler
Open in Compilra IDE
Run and test Java on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.