BCA / B.Tech 14 min read

Exception Handling in Java

Exception Handling in Java:


What is an Exception?

When an error occurs during the runtime of a program, it is called an Exception.

An "Exception" is an unexpected problem that can halt the execution of the program.

Real-life example: Suppose you are driving and suddenly a pothole appears on the road. You either apply the brakes or swerve the car.
Pothole (Error) → Exception
Applying brakes or swerving (Handling it) → Exception Handling

Why do exceptions occur in Java?

Some common reasons for exceptions:
  • Dividing a number by 0 (ArithmeticException)
  • Accessing an array index out of bounds (ArrayIndexOutOfBoundsException)
  • Accessing a null value (NullPointerException)
  • Entering the wrong type of data (InputMismatchException)
  • File not found (FileNotFoundException)

Example (Divide by Zero Exception):
public class Example {
    public static void main(String[] args) {
        int a = 10, b = 0;
        int result = a / b; // Error will occur here (ArithmeticException)
        System.out.println("Result: " + result);
    }
}
Error:
Exception in thread "main" java.lang.ArithmeticException: / by zero

Why is Exception Handling important?

  • If an exception is not handled:
  • The program might crash.
  • Data loss can occur.
  • The user experience can be poor.
  • Therefore, Exception Handling is used to ensure the program runs smoothly and errors are handled correctly.

How to handle exceptions in Java?
There are 5 keywords for exception handling in Java: `try`, `catch`, `finally`, `throw`, and `throws`.

Try-Catch Block (Exception Handling Example)
public class TryCatchExample {
    public static void main(String[] args) {
        try {
            int a = 10, b = 0;
            int result = a / b; // Exception will occur here
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error: Cannot divide a number by 0!");
        }
        System.out.println("Program is running normally.");
    }
}
Output:
Error: Cannot divide a number by 0!
Program is running normally.

  • Try Block: The code that might throw an error is placed in the try block.
  • Catch Block: This block is executed when an error occurs.
  • The catch block has an Exception object (e) from which an error message can be retrieved.
Finally Block (Code that always executes)

The `finally` block always executes, whether an exception occurs or not.
public class FinallyExample {
    public static void main(String[] args) {
        try {
            int a = 10 / 0;
        } catch (ArithmeticException e) {
            System.out.println("Error: Cannot divide by 0!");
        } finally {
            System.out.println("This code will always run.");
        }
    }
}
Output:
Error: Cannot divide by 0!
This code will always run.
The `finally` block is used for closing files, connections, etc.

Throw and Throws (Manually throwing an exception)

The `throw` keyword is used to manually throw an exception.
public class ThrowExample {
    static void checkAge(int age) {
        if (age < 18) {
            throw new ArithmeticException("You are not eligible to vote yet!");
        } else {
            System.out.println("You can vote.");
        }
    }

    public static void main(String[] args) {
        checkAge(16); // Exception will be thrown here
    }
}
Output:
Exception in thread "main" java.lang.ArithmeticException: You are not eligible to vote yet!

Custom Exception (Creating your own exceptions)

If we need to create a specific type of exception, we can create a Custom Exception Class.
class MyException extends Exception {
    public MyException(String message) {
        super(message);
    }
}

public class CustomExceptionExample {
    static void checkNumber(int num) throws MyException {
        if (num < 0) {
            throw new MyException("Negative numbers are not acceptable!");
        }
    }

    public static void main(String[] args) {
        try {
            checkNumber(-5);
        } catch (MyException e) {
            System.out.println("Caught Exception: " + e.getMessage());
        }
    }
}
Output:
Caught Exception: Negative numbers are not acceptable!