DEV Community

Cover image for “Why Exception Handling is Crucial in Java (With Examples)”
Arul .A
Arul .A

Posted on

“Why Exception Handling is Crucial in Java (With Examples)”

What is Exception Handling?

Exception handling is a mechanism to handle runtime errors so your program doesn’t crash abruptly.

  1. Prevents Program Crash

Without exception handling, your program stops immediately when an error occurs.

❌ Without Exception Handling:

int a = 10;
int b = 0;
System.out.println(a / b); // Crash: ArithmeticException
System.out.println("Program continues"); // Never runs
Enter fullscreen mode Exit fullscreen mode

✅ With Exception Handling:

try {
    int a = 10;
    int b = 0;
    System.out.println(a / b);
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero");
}

System.out.println("Program continues");
Enter fullscreen mode Exit fullscreen mode

2.Maintains Normal Program Flow :

Even if an error happens, the rest of the code still runs.

try {
    int arr[] = {1, 2, 3};
    System.out.println(arr[5]); // Error
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Invalid index");
}

System.out.println("Next task executed");
Enter fullscreen mode Exit fullscreen mode

3.Separating Error-Handling Code from "Regular" Code

-Normal Code :

errorCodeType readFile {
    initialize errorCode = 0;

    open the file;
    if (theFileIsOpen) {
        determine the length of the file;
        if (gotTheFileLength) {
            allocate that much memory;
            if (gotEnoughMemory) {
                read the file into memory;
                if (readFailed) {
                    errorCode = -1;
                }
            } else {
                errorCode = -2;
            }
        } else {
            errorCode = -3;
        }
        close the file;
        if (theFileDidntClose && errorCode == 0) {
            errorCode = -4;
        } else {
            errorCode = errorCode and -4;
        }
    } else {
        errorCode = -5;
    }
    return errorCode;
}
Enter fullscreen mode Exit fullscreen mode

Exception with code :

readFile {
    try {
        open the file;
        determine its size;
        allocate that much memory;
        read the file into memory;
        close the file;
    } catch (fileOpenFailed) {
       doSomething;
    } catch (sizeDeterminationFailed) {
        doSomething;
    } catch (memoryAllocationFailed) {
        doSomething;
    } catch (readFailed) {
        doSomething;
    } catch (fileCloseFailed) {
        doSomething;
    }
}
Enter fullscreen mode Exit fullscreen mode
  1. Helps in Debugging :

    You can print error details to understand the problem.

try {
    int a = 5 / 0;
} catch (Exception e) {
    e.printStackTrace();
}
Enter fullscreen mode Exit fullscreen mode
  • It Shows exact error and line number.
  1. Allows Custom Error Messages :

-You can give meaningful feedback instead of cryptic errors.
User-friendly error handling.

try {
    int age = -5;
    if (age < 0) {
        throw new IllegalArgumentException("Age cannot be negative");
    }
} catch (IllegalArgumentException e) {
    System.out.println(e.getMessage());
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)