Exception Handling in Java - Beginner Friendly Notes
1. What is an Exception?
An exception is an event that disrupts the normal flow of your program.
Example: int x = 5 / 0; // causes ArithmeticException
2. Why Exception Handling?
Without handling: program crashes.
With handling: shows error message and continues.
3. Keywords:
- try: risky code
- catch: handles error
- finally: always runs
- throw: manually throws error
- throws: declares error in method
4. Types:
- Checked: must handle (e.g., IOException)
- Unchecked: runtime errors (e.g., ArithmeticException)
- Error: serious problems (e.g., OutOfMemoryError)
5. Exception Hierarchy:
Throwable -> Exception -> RuntimeException
-> Error
6. Multiple Catch:
Use to handle different exceptions separately.
7. Combined Catch (Java 7+):
catch (IOException | SQLException e) { }
8. Nested try:
try inside another try for finer control.
9. throw Example:
throw new ArithmeticException("error");
10. throws Example:
public void readFile() throws IOException
11. finally Example:
Always runs whether error occurs or not.
12. Custom Exception:
class MyException extends Exception { }
Real-Life Analogy:
try -> ATM connecting
catch -> "No Network"
finally -> print receipt
throw -> force error (e.g., wrong PIN)
throws -> ATM process may error