Java Exception Handling: Types, Keywords, Examples, and Best Practices

 

Java Exception Handling Guide

Master the art of handling errors gracefully in Java applications

Introduction

In Java, exceptions are events that disrupt the normal flow of a program. Exception handling is a mechanism to deal with such events gracefully without crashing the program.

Example: Dividing a number by zero would normally stop a program, but with exception handling, you can show a friendly message instead.

What is an Exception?

An exception is an object that represents an error or unexpected behavior that occurs during program execution.

Why Exception Handling is Important

  • Prevents program crashes
  • Makes code more reliable
  • Helps debug issues more easily

Types of Exceptions in Java

1. Checked Exceptions

  • Checked at compile-time
  • Must be handled using try-catch or declared using throws
  • Example: IOException, SQLException

2. Unchecked Exceptions

  • Checked at runtime
  • Caused mostly by programming errors
  • Example: ArithmeticException, NullPointerException

3. Errors

  • Serious problems that applications should not try to handle
  • Example: OutOfMemoryError

Exception Hierarchy

java.lang.Object
↳ java.lang.Throwable
  ↳ java.lang.Exception
    ↳ Checked & Unchecked Exceptions
  ↳ java.lang.Error

Keywords in Exception Handling

try

The block of code that might throw an exception.

catch

Handles the exception if it occurs.

finally

Block that always executes, whether an exception occurs or not.

throw

Used to explicitly throw an exception.

throws

Used in method signature to declare exceptions that a method might throw.

Exception Handling Examples

Basic Example

public class Example1 {
  public static void main(String[] args) {
    try {
      int result = 10 / 0; // Risky code
    } catch (ArithmeticException e) {
      System.out.println("Cannot divide by zero!");
    }
  }
}
Output: Cannot divide by zero!
Explanation: The try block throws ArithmeticException. The catch block catches it and prints the message.

Multiple Catch Blocks

public class Example2 {
  public static void main(String[] args) {
    try {
      String str = null;
      System.out.println(str.length());
    } catch (ArithmeticException e) {
      System.out.println("Arithmetic Exception occurred");
    } catch (NullPointerException e) {
      System.out.println("Null Pointer Exception occurred");
    }
  }
}
Output: Null Pointer Exception occurred
Explanation: Only the matching catch block runs.

Nested try Blocks

public class Example3 {
  public static void main(String[] args) {
    try {
      try {
        int arr[] = {1, 2, 3};
        System.out.println(arr[5]);
      } catch (ArrayIndexOutOfBoundsException e) {
        System.out.println("Array index is out of bounds!");
      }
      int num = 10 / 0;
    } catch (ArithmeticException e) {
      System.out.println("Cannot divide by zero!");
    }
  }
}
Output:
Array index is out of bounds!
Cannot divide by zero!

finally Block

public class Example4 {
  public static void main(String[] args) {
    try {
      int num = 5 / 0;
    } catch (ArithmeticException e) {
      System.out.println("Exception caught");
    } finally {
      System.out.println("This will always execute");
    }
  }
}
Output:
Exception caught
This will always execute

throw Keyword

public class Example5 {
  public static void validateAge(int age) {
    if (age < 18) {
      throw new ArithmeticException("Not eligible to vote");
    }
    System.out.println("Eligible to vote");
  }
  public static void main(String[] args) {
    validateAge(15);
  }
}
Output:
Exception in thread "main" java.lang.ArithmeticException: Not eligible to vote

throws Keyword

import java.io.*;
public class Example6 {
  public static void readFile() throws IOException {
    FileReader fr = new FileReader("test.txt");
    fr.read();
    fr.close();
  }
  public static void main(String[] args) {
    try {
      readFile();
    } catch (IOException e) {
      System.out.println("File handling error: " + e.getMessage());
    }
  }
}
Output:
File handling error: test.txt (No such file or directory)

Custom Exceptions

class MyException extends Exception {
  public MyException(String message) {
    super(message);
  }
}

public class Example7 {
  public static void main(String[] args) {
    try {
      throw new MyException("Custom exception occurred!");
    } catch (MyException e) {
      System.out.println(e.getMessage());
    }
  }
}
Output: Custom exception occurred!

Common Built-in Exceptions

ArithmeticException

Thrown when exceptional arithmetic condition occurs (e.g., division by zero)

NullPointerException

Thrown when trying to use null where an object is required

ArrayIndexOutOfBoundsException

Thrown when accessing an array with an illegal index

NumberFormatException

Thrown when converting an invalid string to a numeric type

IOException

Thrown when an I/O operation fails or is interrupted

Best Practices

  • Handle only what you can actually recover from
  • Log exceptions for debugging
  • Avoid catching Exception blindly
  • Use custom exceptions for meaningful errors
  • Clean up resources in finally blocks
  • Provide meaningful exception messages

Conclusion

Exception handling in Java is essential for building robust, crash-proof applications. By mastering try, catch, finally, throw, and throws, you can manage errors effectively and keep your programs running smoothly. Understanding the different types of exceptions and when to use each approach will make your code more resilient and maintainable.

Frequently Asked Questions

Q1: What is the difference between checked and unchecked exceptions?

A: Checked exceptions are checked at compile-time; unchecked are checked at runtime.

Q2: Can finally block be skipped?

A: Yes, if the JVM exits using System.exit() before it runs.

Q3: Can we have multiple catch blocks?

A: Yes, to handle different exception types.

Q4: Is it possible to have try without catch?

A: Yes, but only if there is a finally block.

Q5: Why create custom exceptions?

A: For more meaningful and domain-specific error handling.


Post a Comment

0 Comments