Exception Handling Of Java

 Exception handling in Java allows developers to manage unexpected or exceptional situations that may occur during program execution. Here's an overview of exception handling in Java:

Types of Exceptions:

  1. Checked Exceptions:

    • Checked exceptions are exceptions that the compiler requires you to handle explicitly. They are subclasses of Exception but not RuntimeException.
    • Examples include IOException, SQLException, etc.
  2. Unchecked Exceptions (Runtime Exceptions):

    • Unchecked exceptions are exceptions that do not need to be declared explicitly in a method or constructor's throws clause.
    • Examples include NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException, etc.
  3. Errors:

    • Errors are exceptional scenarios that are out of the control of the application and should not be caught or handled. Examples include OutOfMemoryError, StackOverflowError, etc.

Exception Handling Keywords:

  1. try-catch Block:

    • The try block contains the code that may throw an exception.
    • The catch block catches and handles the exception.

  2. try { // Code that may throw an exception } catch (ExceptionType e) { // Handling the exception }

finally Block:

  • The finally block is optional and is used to execute code that must be run regardless of whether an exception occurred.

try {
    // Code that may throw an exception
} catch (Exception e) {
    // Handling the exception
} finally {
    // Code that always executes
}

throw Keyword:

  • The throw keyword is used to explicitly throw an exception.

throw new ExceptionType("Error message");

throws Keyword:

  • The throws keyword is used in method declarations to indicate that the method may throw certain exceptions.

void methodName() throws ExceptionType { // Method code }

Example:

import java.io.*;

public class ExceptionHandlingExample {
    public static void main(String[] args) {
        try {
            // Code that may throw an exception
            BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
            String line = reader.readLine();
            System.out.println(line);
            reader.close();
        } catch (FileNotFoundException e) {
            // Handling FileNotFoundException
            System.out.println("File not found: " + e.getMessage());
        } catch (IOException e) {
            // Handling IOException
            System.out.println("Error reading file: " + e.getMessage());
        } finally {
            // Closing resources or cleanup code
            System.out.println("Finally block executed");
        }
    }
}

In this example, the try block attempts to read from a file. If a FileNotFoundException or IOException occurs, it is caught and handled in the respective catch block. The finally block ensures that resources are properly closed, regardless of whether an exception occurred.

Post a Comment

0 Comments