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
This structure lets the program continue instead of crashing.
5️⃣ Types of Exceptions
✅ Checked Exceptions
✅ Unchecked Exceptions
✅ Errors
6️⃣ How Exception Handling Works Internally
-
JVM runs code inside try
-
If an error occurs → remaining try code skipped
-
JVM searches for matching catch
-
Executes catch if found
-
Executes finally block
-
If no handler found → exception propagates and program ends