Programming Pandit

c/c++/c#/Javav/Python


Latest Update

Tuesday, March 11, 2025

Throwing and Catching Exceptions in Java

 

📌 Throwing Exceptions

In Java, exceptions can be thrown explicitly using the throw keyword or can be generated by the JVM implicitly during runtime errors.

🔍 Explicit Throwing of Exceptions

You can throw an exception manually using the throw keyword. Typically used to signal an error condition as per custom requirements.

Syntax:

throw new ExceptionType("Error Message");


🔍 Example of Throwing Exceptions

public class ThrowExample {

    public static void checkAge(int age) {

        if (age < 18) {

            throw new IllegalArgumentException("Age must be 18 or older.");

        }

        System.out.println("Access granted.");

    }

 

    public static void main(String[] args) {

        checkAge(15);  // This will cause an exception to be thrown

    }

}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: Age must be 18 or older.

        at ThrowExample.checkAge(ThrowExample.java:5)

        at ThrowExample.main(ThrowExample.java:9)


📌 Catching Exceptions

Catching exceptions is done using a try-catch block. The exception is caught when the program control transfers to the catch block.

🔍 Syntax:

try {

    // Code that may produce an exception

} catch (ExceptionType e) {

    // Code to handle the exception

}


📌 Catching Multiple Exceptions

You can catch multiple exceptions using multiple catch blocks or multi-catch block (introduced in Java 7).

🔍 Example of Catching Exceptions

public class CatchExample {

    public static void main(String[] args) {

        try {

            int[] numbers = {1, 2, 3};

            System.out.println(numbers[5]);  // ArrayIndexOutOfBoundsException

 

            int result = 10 / 0;  // ArithmeticException

        } catch (ArrayIndexOutOfBoundsException e) {

            System.out.println("Array index is out of bounds.");

        } catch (ArithmeticException e) {

            System.out.println("Cannot divide by zero.");

        }

    }

}

Output:

Array index is out of bounds.


📌 Using Multi-Catch Block (Java 7+)

You can catch multiple exceptions in a single catch block using the pipe (|) symbol.

public class MultiCatchExample {

    public static void main(String[] args) {

        try {

            int[] numbers = {1, 2, 3};

            System.out.println(numbers[5]); // This will cause an exception

        } catch (ArrayIndexOutOfBoundsException | ArithmeticException e) {

            System.out.println("Exception caught: " + e.getMessage());

        }

    }

}

Output:

Exception caught: Index 5 out of bounds for length 3


📌 The finally Block

The finally block is always executed whether an exception is thrown or not. It is generally used to release resources like file streams, database connections, etc.

🔍 Example:

public class FinallyExample {

    public static void main(String[] args) {

        try {

            int result = 10 / 0;

        } catch (ArithmeticException e) {

            System.out.println("Exception caught: " + e);

        } finally {

            System.out.println("Execution of the finally block.");

        }

    }

}

Output:

Exception caught: java.lang.ArithmeticException: / by zero

Execution of the finally block.


📌 Using throws Keyword

The throws keyword is used in method signatures to indicate that a method may throw an exception. It doesn't handle the exception, but allows the caller to handle it.

🔍 Example:

import java.io.*;

 

public class ThrowsExample {

    public static void readFile() throws IOException {

        FileInputStream file = new FileInputStream("nonexistentfile.txt");

    }

 

    public static void main(String[] args) {

        try {

            readFile();

        } catch (IOException e) {

            System.out.println("File not found: " + e.getMessage());

        }

    }

}

Output:

File not found: nonexistentfile.txt (No such file or directory)


📌 Exception Handling Best Practices

  1. Catch Specific Exceptions: Always catch specific exceptions before catching the generic Exception class.
  2. Use finally Blocks for Cleanup: Ensure resources are properly released.
  3. Avoid Empty catch Blocks: Always handle exceptions properly.
  4. Use throws Keyword When Necessary: When a method cannot handle an exception, delegate it to the caller.
  5. Create Custom Exceptions: When applicable, for better error reporting and clarity.

 

No comments:

Post a Comment