DEV Community

Sudhakar V
Sudhakar V

Posted on

Exception Handling in Java

Exception handling in Java is a mechanism to handle runtime errors (exceptions) so that the normal flow of the program can be maintained. Java provides keywords like try, catch, finally, throw, and throws to manage exceptions.


Types of Exceptions

  1. Checked Exceptions (Compile-time exceptions)
    • Must be handled explicitly (e.g., IOException, SQLException).
  2. Unchecked Exceptions (Runtime exceptions)
    • Not checked at compile time (e.g., NullPointerException, ArithmeticException).
  3. Errors
    • Serious problems beyond application control (e.g., OutOfMemoryError).

Exception Handling Keywords

1. try-catch Block

  • try → Contains code that might throw an exception.
  • catch → Handles the exception if it occurs.

Example: Handling ArithmeticException

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

Output:

Cannot divide by zero!
Enter fullscreen mode Exit fullscreen mode

2. finally Block

  • Always executes, whether an exception occurs or not.
  • Used for cleanup (e.g., closing files, database connections).

Example: finally Usage

public class FinallyDemo {
    public static void main(String[] args) {
        try {
            int[] arr = {1, 2, 3};
            System.out.println(arr[5]); // Throws ArrayIndexOutOfBoundsException
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array index out of bounds!");
        } finally {
            System.out.println("This will always run.");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Array index out of bounds!
This will always run.
Enter fullscreen mode Exit fullscreen mode

3. throw Keyword

  • Used to explicitly throw an exception.

Example: Custom Exception

public class ThrowDemo {
    public static void checkAge(int age) {
        if (age < 18) {
            throw new ArithmeticException("Age must be 18+");
        } else {
            System.out.println("Access granted.");
        }
    }

    public static void main(String[] args) {
        checkAge(15); // Throws ArithmeticException
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Exception in thread "main" java.lang.ArithmeticException: Age must be 18+
Enter fullscreen mode Exit fullscreen mode

4. throws Keyword

  • Declares that a method might throw an exception (used in method signature).

Example: throws in Method

import java.io.*;

public class ThrowsDemo {
    public static void readFile() throws IOException {
        FileReader file = new FileReader("test.txt");
        BufferedReader br = new BufferedReader(file);
        System.out.println(br.readLine());
        br.close();
    }

    public static void main(String[] args) {
        try {
            readFile(); // Must handle IOException
        } catch (IOException e) {
            System.out.println("File not found!");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Output (if file doesn't exist):

File not found!
Enter fullscreen mode Exit fullscreen mode

Best Practices

Catch specific exceptions (not just Exception).

Use finally for cleanup (e.g., closing resources).

Log exceptions (using e.printStackTrace() or logging frameworks).

Avoid empty catch blocks (they hide errors).


Summary Table

Keyword Purpose
try Contains risky code
catch Handles exceptions
finally Always executes
throw Manually throws exception
throws Declares exceptions in method signature

Final Example: Full Exception Handling

import java.io.*;

public class FullExceptionHandling {
    public static void main(String[] args) {
        try {
            FileReader file = new FileReader("nonexistent.txt");
            int data = file.read();
            System.out.println(data);
        } catch (FileNotFoundException e) {
            System.out.println("File not found!");
        } catch (IOException e) {
            System.out.println("IO Error!");
        } finally {
            System.out.println("Execution complete.");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

File not found!
Execution complete.
Enter fullscreen mode Exit fullscreen mode

Conclusion

Exception handling ensures robustness and graceful failure in Java programs. Use try-catch for handling errors, finally for cleanup, and throw/throws for custom exceptions. 🚀

Top comments (0)