Exception Handling in Java

 

Exception Handling in Java

Exception handling is a powerful mechanism in Java to handle runtime errors and maintain the normal flow of an application. It is a mechanism to handle exceptions (unexpected events or errors) that may occur during program execution.


What is an Exception?

An exception is an event that disrupts the normal flow of a program. It is an object that represents an error or a condition that needs special processing. For example:

  • Dividing a number by zero
  • Accessing an invalid array index
  • Opening a non-existent file

Types of Exceptions

  1. Checked Exceptions

    • These are exceptions checked at compile-time.
    • Examples: IOException, SQLException
    • The programmer must handle these exceptions using a try-catch block or declare them using the throws keyword.
  2. Unchecked Exceptions

    • These are exceptions that occur at runtime and are not checked during compilation.
    • Examples: ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException
    • These exceptions occur due to programming errors.
  3. Errors

    • These are serious problems that a program cannot typically handle.
    • Examples: OutOfMemoryError, StackOverflowError

Exception Handling Keywords in Java

Java provides five keywords to handle exceptions:

  1. try

    • Contains the code that might throw an exception.
    • Example:
      try {
      int result = 10 / 0; }
  2. catch

    • Handles the exception thrown in the try block.
    • Example:
      catch (ArithmeticException e) {
      System.out.println("Cannot divide by zero."); }
  3. finally

    • Contains code that will always execute, whether an exception is thrown or not.
    • Used for cleanup activities like closing a file or releasing a resource.
    • Example:
      finally {
      System.out.println("Execution complete."); }
  4. throw

    • Used to explicitly throw an exception.
    • Example:
      throw new ArithmeticException("Invalid operation");
  5. throws

    • Declares the exceptions that a method might throw.
    • Example:
      void readFile() throws IOException {
      // Code to read a file }

Syntax of Exception Handling

try {
// Code that may throw an exception } catch (ExceptionType e) { // Code to handle the exception } finally { // Code that will always execute }

Example: Exception Handling in Java

public class ExceptionExample {
public static void main(String[] args) { try { int data = 50 / 0; // This will throw ArithmeticException } catch (ArithmeticException e) { System.out.println("Exception caught: " + e); } finally { System.out.println("Finally block is executed."); } } }

Output:

Exception caught: java.lang.ArithmeticException: / by zero
Finally block is executed.

Advantages of Exception Handling

  1. Maintains Program Flow
    It allows the program to continue running even after an error.

  2. Separates Error-Handling Code
    Keeps the main logic separate from error-handling code, improving readability.

  3. Better Debugging
    Provides detailed information about the error for debugging purposes.

  4. Ensures Resource Management
    Ensures resources (like files or database connections) are closed properly in the finally block.


Hierarchy of Exception Classes

  1. Throwable (Root class)
    • Exception
      For recoverable conditions (e.g., IOException).
    • Error
      For serious conditions (e.g., OutOfMemoryError).

Hierarchy Example:

Throwable
|-- Exception |-- IOException |-- SQLException |-- RuntimeException |-- ArithmeticException |-- NullPointerException |-- Error |-- OutOfMemoryError |-- StackOverflowError

Best Practices for Exception Handling

  1. Catch specific exceptions rather than using a general Exception class.
  2. Use the finally block to release resources.
  3. Avoid swallowing exceptions (e.g., empty catch blocks).
  4. Log exceptions using logging frameworks like Log4j or java.util.logging.
  5. Avoid overusing exceptions for regular program control flow.

Commonly Used Built-in Exceptions in Java

  1. ArithmeticException - Division by zero, overflow, etc.
  2. NullPointerException - Accessing a null reference.
  3. ArrayIndexOutOfBoundsException - Invalid array indexing.
  4. NumberFormatException - Converting an invalid string to a number.
  5. IOException - Input/output operation failures.

Comments

Popular posts from this blog

Programming Notes by Atul Kalukhe