DEV Community

Jayashree
Jayashree

Posted on

Exception Handling in Java – Complete Guide for Beginners

Exception handling

Exception handling is one of the most important concepts in Java. It helps developers manage runtime errors gracefully without crashing the program.

What is an Exception?

An exception is an unexpected event that occurs during program execution and disrupts the normal flow.

Example:

int a = 10;
int b = 0;
int result = a / b; // ArithmeticException
Enter fullscreen mode Exit fullscreen mode

Why Exception Handling?

Without exception handling:

  • Program will terminate abruptly
  • User experience becomes poor

With exception handling:

  • Program continues execution
  • Errors can be handled properly

Types of Exceptions in Java

1. Checked Exceptions

  • Checked at compile-time
  • Must be handled using try-catch or declared using throws

Examples:

  • IOException
  • SQLException

2. Unchecked Exceptions

  • Occur at runtime
  • Not mandatory to handle

Examples:

  • ArithmeticException
  • NullPointerException
  • ArrayIndexOutOfBoundsException

Exception Handling Keywords

1. try

Wrap the code that may cause an exception.

2. catch

Handles the exception.

3. finally

Always executes (used for cleanup).

4. throw

Used to explicitly throw an exception.

5. throws

Declares exceptions in method signature.

Basic Syntax

try {
    // risky code
} catch (Exception e) {
    // handling code
} finally {
    // cleanup code
}
Enter fullscreen mode Exit fullscreen mode

Example Program

class Example {
    public static void main(String[] args) {
        try {
            int num = 10 / 0;
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero");
        } finally {
            System.out.println("Execution completed");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Multiple Catch Blocks

try {
    int arr[] = new int[5];
    arr[10] = 50;
} catch (ArithmeticException e) {
    System.out.println("Arithmetic Error");
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Array Index Error");
}
Enter fullscreen mode Exit fullscreen mode

throw Keyword Example

throw new ArithmeticException("Manual Exception");
Enter fullscreen mode Exit fullscreen mode

throws Keyword Example

void readFile() throws IOException {
    // code
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Exception handling in Java ensures that your program runs smoothly even when errors occur. Mastering this concept is essential for building robust and reliable applications.

👉 In short:
Exception handling = Handling errors without stopping the program

Top comments (0)