DEV Community

Hayes vincent
Hayes vincent

Posted on

Java Exception Handling:

What is an Exception?

An exception is an unwanted or unexpected event that occurs during the execution of a program, which disrupts the normal flow of instructions.

In simple terms:
It is a runtime error that can crash your program if not handled properly.

Real-Life Examples
Dividing a number by zero
Accessing an invalid array index
Opening a file that doesn’t exist
πŸ”Ή Exception Hierarchy in Java

All exceptions in Java follow a structured hierarchy under Throwable Class

Object
└── Throwable
β”œβ”€β”€ Exception
β”‚ β”œβ”€β”€ Checked Exceptions
β”‚ └── Unchecked Exceptions (RuntimeException)
└── Error
πŸ”Έ Important Concept
Most exceptions are derived from Exception
Error represents serious system-level problems (not usually handled)
** Types of Exceptions**

1. Checked Exceptions
Checked at compile time
Must be handled using try-catch or throws

Example:

IOException
SQLException

** 2. Unchecked Exceptions (Runtime Exceptions)**
Occur at runtime
Not mandatory to handle

Example:
**
ArithmeticException
NullPointerException
ArrayIndexOutOfBoundsException**

** Try-Catch Block**

The try-catch block is used to handle exceptions and prevent program crashes.

Syntax

try {
    // Code that may cause exception
} catch (ExceptionType e) {
    // Code to handle exception
}
πŸ”Ή Example: Handling Arithmetic Exception
public class Test {
    public static void main(String[] args) {
        try {
            int result = 10 / 0; // risky code
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero!");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Multiple Catch Blocks

You can handle different types of exceptions separately.

try {
    int arr[] = new int[3];
    arr[5] = 10;
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Index out of bounds!");
} catch (Exception e) {
    System.out.println("Some error occurred");
}
Enter fullscreen mode Exit fullscreen mode

Finally Block

The finally block always executes, whether an exception occurs or not.

Used for:

Closing files
Releasing resources

try {
    int data = 100 / 10;
} catch (Exception e) {
    System.out.println("Error");
} finally {
    System.out.println("Execution completed");
}
Enter fullscreen mode Exit fullscreen mode

Common Exception Types in Java

** 1. ArithmeticException**

Occurs when an illegal arithmetic operation is performed.

int x = 10 / 0;

2. NullPointerException

Occurs when trying to use a null reference.


String str = null;
System.out.println(str.length());

Enter fullscreen mode Exit fullscreen mode

3. ArrayIndexOutOfBoundsException

Occurs when accessing an invalid array index.


int arr[] = {1, 2, 3};
System.out.println(arr[5]);

Enter fullscreen mode Exit fullscreen mode

**
Why Exception Handling is Important?**

Prevents program crashes
Maintains smooth execution
Improves code reliability
Helps in debugging

Final Thoughts

Exception handling is a core concept in Java that every developer must understand. By using try, catch, and finally, you can manage errors effectively and build robust applications.

Top comments (0)