An exception is an unexpected event that occurs during program execution and disrupts normal flow.
Java handles exceptions using try-catch mechanism, allowing your app to fail gracefully.
Exception Hierarchy (Simplified)
Throwable
βββ Error (not recoverable)
βββ Exception
βββ Checked Exceptions (must be handled)
βββ Unchecked Exceptions (RuntimeException)
Basic try-catch Example
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Can't divide by zero!");
}
Keywords
Keyword | Purpose |
---|---|
try | Wraps risky code |
catch | Handles specific exception types |
finally | Returns no matter what (cleanup code) |
throw | Manually throw an exception |
throws | Declare exceptions a method might throw |
Try-Catch-Finally
try {
int[] nums = {1, 2};
System.out.println(nums[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index error!");
} finally {
System.out.println("Cleanup code runs here.");
}
Throw & Throws
void checkAge(int age) throws IllegalArgumentException {
if (age < 18) {
throw new IllegalArgumentException("Too young");
}
}
Checked vs Unchecked Exceptions
Type | Handled at Compile Time? | Example |
---|---|---|
Checked | Yes | IOException, SQLException |
Unchecked | No | NullPointerException, ArithmeticException |
Tip
Be ready to explain:
- wy unchecked exceptions arenβt forced to be caught,
- difference between throw and throws,
- use of finally for resource cleanup,
- custom exceptions (class MyException extends Exception).
Parent: _Exceptions