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

 
public class Test { public static void main(String[] args) { try { int result = 10 / 0; // causes exception } catch (ArithmeticException e) { System.out.println("Cannot divide by zero!"); } finally { System.out.println("Program finished."); } } }

How it works

  • try executes risky code

  • Division by zero throws ArithmeticException

  • catch handles it

  • finally runs 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

 

  1. JVM runs code inside try

  2. If an error occurs → remaining try code skipped

  3. JVM searches for matching catch

  4. Executes catch if found

  5. Executes finally block

  6. If no handler found → exception propagates and program ends