Home / Questions / How Java Handles Exceptions
Explanatory Question

How Java Handles Exceptions

👁 24 Views
📘 Detailed Answer
🕒 Easy to Read
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.

Answer with Explanation

Java uses a mechanism called Exception Handling with these keywords:

Keyword Purpose
try Defines a block of code to test for errors
catch Defines a block of code to handle the error
finally Always executes (cleanup code)
throw Used to throw an exception manually
throws Declares exceptions that a method might throw

✅ Example: Handling an Exception


public class Example {
    public static void main(String[] args) {
        try {
            int a = 10;
            int b = 0;
            int result = a / b;   // may cause an exception
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error: Cannot divide by zero!");
        } finally {
            System.out.println("Execution completed.");
        }
    }
}

Output:


Error: Cannot divide by zero!
Execution completed.