DEV Community

Arun Kumar
Arun Kumar

Posted on

Java Exception Handling: Try, Catch & Common Exception Types

What is an Exception?

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

Example:

  • Dividing a number by zero
  • Accessing an invalid array index
  • Trying to open a file that doesn’t exist

Exception Hierarchy in Java

In Java, all exceptions are part of a class hierarchy.

Object
  └── Throwable
        ├── Exception
        │     ├── Checked Exceptions
        │     └── Unchecked Exceptions (RuntimeException)
        └── Error
Enter fullscreen mode Exit fullscreen mode

Important Concept:
Every exception class in Java is either a direct or indirect child of the Exception class (except Error, which represents serious system issues).


##  Try-Catch Block

The `try-catch` block is used to handle exceptions.

###  Syntax:

java
try {
    // Code that may cause exception
} catch (ExceptionType e) {
    // Code to handle exception
}

Enter fullscreen mode Exit fullscreen mode

Example:

public class Test {
    public static void main(String[] args) {
        try {
            int result = 10 / 0; // risky code
        } catch (Arithmetic Exception e) {
            System.out.println("Cannot divide by zero!");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Multiple Catch Blocks

You can handle different 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.

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

1️ ArithmeticException

Occurs when an illegal arithmetic operation is performed.

int x = 10 / 0;
Enter fullscreen mode Exit fullscreen mode

2️NullPointerException

Occurs when trying to use a null reference.
java

String str = null;
System.out.println(str.length());
Enter fullscreen mode Exit fullscreen mode

3️ ArrayIndexOutOfBoundsException

Occurs when accessing an invalid array index.

java

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

Top comments (0)