Java Exception Handling Explained (Try-Catch, Finally)

Java Exception Handling Explained (Try-Catch, Finally) with Examples

Exception handling is one of the most important concepts in Java and is frequently asked in interviews.

It helps prevent your program from crashing and allows you to handle errors properly.

Exception handling ensures your program continues running even when errors occur.

Written by Shivkumar Udas – Engineering student sharing practical Java guides for beginners.

Exception handling ensures your program continues running even when errors occur.


๐Ÿ’ก What is Exception in Java?

An exception is an event that disrupts the normal flow of a program.

For example, dividing a number by zero causes an exception.


๐Ÿ“Œ Types of Exceptions

  • Checked Exceptions – Checked at compile time (e.g., IOException)
  • Unchecked Exceptions – Occur at runtime (e.g., ArithmeticException)

๐Ÿ”น Try-Catch Block

The try block contains code that may throw an exception, and the catch block handles it.


public class Example {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;
        } catch (ArithmeticException e) {
            System.out.println("Error: Cannot divide by zero");
        }
    }
}

๐Ÿ”น Finally Block

The finally block always executes, whether an exception occurs or not.


try {
    int result = 10 / 2;
} catch (Exception e) {
    System.out.println("Error");
} finally {
    System.out.println("This always executes");
}

๐Ÿ”น Multiple Catch Blocks

You can handle different exceptions using multiple catch blocks.


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

๐Ÿ“Š Exception Handling Flow

  • Try block executes
  • If exception occurs → catch block executes
  • Finally block always executes

⚡ Why Exception Handling is Important

  • Prevents program crashes
  • Improves code reliability
  • Helps in debugging

๐ŸŽฏ Interview Tip

Interviewers often ask:

  • Difference between checked and unchecked exceptions
  • When to use try-catch
  • What is finally block

Always explain with examples for better understanding.


๐Ÿงช Practice Task

Create a program that handles division by zero and array index errors using try-catch.


๐Ÿ”— Related Guides


๐ŸŽฏ Conclusion

Exception handling is essential for writing robust and error-free Java programs.

Understanding how to handle exceptions properly will make you a better Java developer.

Comments