bscodinglab

Exception and Error Handling

Exception handling in Java is a mechanism for dealing with errors or exceptional situations that can occur during the execution of a program. In Java, exceptions are objects that represent errors, and you can use try-catch blocks to handle these exceptions. Here’s an overview of exception handling in Java:

1. Throw Exceptions :-

Exceptions are thrown using the throw statement. You can throw built-in exceptions or create custom exceptions by extending the Exception class or one of its subclasses.

Example:- throw new ExceptionType(“Exception message”);

2. Throws Exceptions :-

The throws keyword is used in a method declaration to indicate that the method may throw certain types of exceptions. When you declare a method with the throws keyword, you are specifying that this method might throw exceptions of the specified types, and the caller of this method must handle those exceptions or declare them in their own throws clause.

Syntex:-

            returnType methodName(parameters) throws ExceptionType1, ExceptionType2, …

                 {

                        // method body

                  }

Example:-

public void someMethod() throws IOException

     {

            // method implementation that may throw IOException

       }

3. Catching Exceptions :-

Exceptions are caught and handled using the try-catch block. Inside the try block, you place the code that might throw an exception, and in the catch block, you specify how to handle the exception.

Example:-

try {

            // Code that might throw an exception

    }

catch (ExceptionType e)

    {

             // Handle the exception

      }

4. Multiple Catch Blocks :-

You can have multiple catch blocks to handle different types of exceptions. They are evaluated in the order they are defined, and the first matching catch block is executed.

Example:-

try {

                // Code that might throw an exception

        }

catch (IOException e)

        {

                // Handle IOException

         }

catch (NullPointerException e)

          {

                  // Handle NullPointerException

           }

catch (CustomException e)

           {

                   // Handle CustomException

             }

5. Finally Block :-

You can use a finally block to specify code that must be executed, whether an exception occurs or not. This block is often used for resource cleanup.

Example:-

try {

              // Code that might throw an exception

         }

catch (ExceptionType e)

         {

               // Handle the exception

          }

     finally {

                // Code that always executes

             }

6. Try-With-Resources :-

For handling resources like file I/O or database connections, you can use the try-with-resources statement to automatically close these resources when they are no longer needed.

Example:-

try (BufferedReader reader = new BufferedReader(new FileReader(“file.txt”)))

            {

                        // Code that reads from the file

            }

catch (IOException e)

             {

                         // Handle IOException

            }

7. Custom Exception Classes :-

You can create custom exception classes by extending the Exception class or its subclasses to represent specific error conditions in your application.

Example:-

public class CustomException extends Exception

 {

            public CustomException(String message)

                        {

                                    super(message);

                        }

  }

8. Rethrowing Exceptions :-

You can rethrow an exception in a catch block if you want it to be handled by an outer catch block or to propagate up the call stack.

Example:-

try {

            // Code that might throw an exception

        }

 catch (ExceptionType e)

        {

            // Handle the exception

            throw new AnotherException(“New exception message”);

         }

9. Unchecked vs. Checked Exceptions :-

Checked Exceptions :-

    • Checked exceptions are exceptions that the compiler forces you to handle explicitly in your code. This means you must either catch them using a try-catch block or declare that your method throws them in the method signature using the throws keyword.
    • These exceptions are typically used for situations that your program can anticipate and recover from, such as file input/output operations, network operations, or database connections.
    • Examples of checked exceptions in Java include IOException, SQLException, and ClassNotFoundException.

Unchecked Exceptions :-

    • Unchecked exceptions, also known as runtime exceptions, are exceptions that do not need to be explicitly handled in your code. The compiler does not enforce catching or declaring these exceptions, making them less restrictive compared to checked exceptions.
    • These exceptions usually indicate programming errors, like dividing by zero, accessing an array index out of bounds, or trying to use a null reference. They are meant to be identified and fixed during development.
    • Examples of unchecked exceptions in Java include ArithmeticException, NullPointerException, and ArrayIndexOutOfBoundsException.

Also known as runtime exceptions, these are not checked at compile time. They can occur at runtime, and you are not required to handle them explicitly.

Handling exceptions is crucial for writing robust and reliable Java programs, as it allows you to gracefully handle errors and recover from unexpected situations.

Example:-

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

public class ErrorHandlingExample

  {

      public static void main(String[] args)

          {

   try {

            // Attempt to read a file that may not exist

           BufferedReader reader = new BufferedReader(new fileReader

(“non_existent_file.txt”));

            // Read a line from the file

            String line = reader.readLine();

            // Close the file

            reader.close();

            // Output the line read from the file

            System.out.println(“Contents of the file: ” + line);

                   }

   catch (IOException e)

                    {

            // Handle the exception

            System.err.println(“An error occurred while reading the file:”);

            e.printStackTrace();

 }

   }

    }

In this example :-

  • We attempt to read a file named “non_existent_file.txt” using a BufferedReader inside a try block.
  • The readLine() method may throw an IOException if the file does not exist or if there is an issue with reading it.
  • To handle this potential exception, we catch it in a catch block.
  • In the catch block, we print an error message and the stack trace of the exception using e.printStackTrace(). This helps in diagnosing and debugging the issue.

When you run this code and the file “non_existent_file.txt” does not exist, the IOException will be caught, and the program will display an error message. If the file exists, it will be read, and its contents will be printed.