Java - Exception Handling in Java
1️⃣ What is Exception Handling?
In Java, exception handling is a mechanism used to deal with runtime errors so that a program doesn’t crash and can continue running normally.
An exception is an event that occurs during execution that disrupts the normal flow of instructions (for example dividing by zero or accessing an invalid array index).
Instead of stopping the program abruptly, Java lets you catch and handle such problems using special keywords and blocks.
2️⃣ Why is it important?
-
Prevents sudden program termination
-
Allows graceful error messages
-
Helps maintain normal program flow
-
Makes software more reliable and maintainable
If an exception is not handled, the program may terminate and remaining code won’t run.
3️⃣ Basic Keywords Used
Java provides several keywords for exception handling:
-
try → contains code that might cause an exception
-
catch → handles the exception
-
finally → always executes (cleanup tasks)
-
throw → explicitly creates an exception
-
throws → declares possible exceptions in a method
These blocks work together to detect and manage errors.
The finally block runs whether an exception occurs or not, usually for closing files or releasing resources.
4️⃣ Simple Example
How it works
-
tryexecutes risky code -
Division by zero throws
ArithmeticException -
catchhandles it -
finallyruns regardless of the error
This structure lets the program continue instead of crashing.
5️⃣ Types of Exceptions
✅ Checked Exceptions
-
Checked at compile time
-
Must be handled or declared
-
Example:
IOException
These represent conditions outside the program’s control like file or network issues.
✅ Unchecked Exceptions
-
Occur at runtime
-
Handling is optional
-
Example:
NullPointerException,ArithmeticException
Usually caused by programming mistakes.
✅ Errors
-
Serious issues (e.g., memory failure)
-
Usually not recoverable
-
Example:
OutOfMemoryError
6️⃣ How Exception Handling Works Internally
-
JVM runs code inside
try -
If an error occurs → remaining
trycode skipped -
JVM searches for matching
catch -
Executes
catchif found -
Executes
finallyblock -
If no handler found → exception propagates and program ends