Exception Handling in Java
- Introduction
Exception handling is a powerful mechanism in Java that helps developers manage runtime errors and maintain the normal flow of applications. Instead of crashing the program, Java allows you to handle unexpected situations gracefully using structured blocks like try, catch, and finally.
1.What is an Exception?
An exception is an error that occurs during the execution of a program (runtime error).
👉 Example:
int a = 10;
int b = 0;
int c = a / b; // ArithmeticException
2.Types of Exceptions
✅ Checked Exceptions
- Checked at compile time
- Must be handled using try-catch or throws
- Example: IOException, SQLException
❌ Unchecked Exceptions
- Occur at runtime
- Not mandatory to handle
- Example: NullPointerException, ArithmeticException
3.Important Keywords
- try
Wraps code that may cause an exception.
- catch
Handles the exception.
- finally
Always executes (except when JVM stops).
- throw
Used to explicitly throw an exception.
- throws
Declares exceptions in a method signature.
4.Order of Execution
Correct order:
try → catch → finally
5.Common Exceptions
- Divide by zero → ArithmeticException
- Null value access → NullPointerException
- Invalid array index → ArrayIndexOutOfBoundsException
6.Exception Propagation
Exception propagation means passing an exception from one method to another until it is handled.
void method1() {
int x = 10 / 0;
}
void method2() {
method1();
}
void method3() {
try {
method2();
} catch (Exception e) {
System.out.println("Handled");
}
}
Code Examples
7.Handling Exception
try {
int x = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error");
}
8.Null Handling
try {
String s = null;
System.out.println(s.length());
} catch (Exception e) {
System.out.println("Handled");
}
9.Throw Example
if(marks < 0 || marks > 100){
throw new IllegalArgumentException("Invalid marks");
}
10.SpecialCase:System.exit()
try {
System.exit(0);
} finally {
System.out.println("Finally");
}
Output: Finally will NOT execute
Reason: JVM stops immediately.
11. Purpose of Finally Block
Used for cleanup operations:
Closing files
Releasing resources
Closing database connections
12.Important Rules
try cannot exist alone
Must be followed by catch or finally
catch blocks must be ordered from specific → general
Parent class (Exception) should come last
13.Quick Summary
Exception = Runtime error
try-catch = Handle errors
finally = Cleanup
throw = Create exception
throws = Declare exception
Propagation = Passing exception to caller
14.Conclusion
Exception handling is essential for building robust Java applications. By using proper handling techniques, developers can prevent crashes, improve user experience, and write clean, maintainable code.
Top comments (0)