✏️ Explanatory Question
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 |
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.