1. Introduction to Exception Handling
1.1 What is an Exception
An exception is an event that disrupts the normal flow of a program during execution.
1.2 Errors vs Exceptions
- Errors → Serious issues (system-level)
- Exceptions → Can be handled in code
1.3 Why Exception Handling
- Prevents program crash
- Maintains normal flow
- Improves reliability
1.4 Example
int a = 10;
int b = 0;
System.out.println(a / b); // ArithmeticException
2. Types of Exceptions
2.1 Checked Exceptions
- Checked at compile time
- Example: IOException
2.2 Unchecked Exceptions
- Occur at runtime
- Example: NullPointerException
2.3 Errors
- Not handled by program
- Example: OutOfMemoryError
2.4 Common Exceptions
- ArithmeticException
- NullPointerException
- ArrayIndexOutOfBoundsException
3. try, catch, finally
3.1 try Block
Contains code that may cause exception.
3.2 catch Block
Handles exception.
3.3 finally Block
Always executes (optional).
3.4 Example
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error occurred");
} finally {
System.out.println("Done");
}
3.5 Multiple catch
try {
// code
} catch (ArithmeticException e) {
} catch (NullPointerException e) {
}
4. throw and throws
4.1 throw Keyword
Used to explicitly throw an exception.
throw new ArithmeticException("Error");
4.2 throws Keyword
Declares exceptions in method.
void readFile() throws IOException {
}
4.3 Difference
| throw | throws |
|---|---|
| Used inside method | Used in method declaration |
| Throws one exception | Can declare multiple |
5. Creating Custom Exceptions
5.1 Definition
User-defined exceptions.
5.2 Steps
- Extend Exception class
- Create constructor
- Use throw
5.3 Example
class MyException extends Exception {
MyException(String msg) {
super(msg);
}
}
5.4 Using Custom Exception
void checkAge(int age) throws MyException {
if (age < 18) {
throw new MyException("Not eligible");
}
}
Conclusion
Exception handling is essential for building robust Java applications. By properly handling errors using try-catch blocks and creating custom exceptions, developers can ensure their programs run smoothly even in unexpected situations. Mastering this concept is crucial for real-world application development.