Exception Handling :

Exception handling in Java refers to the mechanism through which errors or exceptional conditions that occur during the program execution are managed and resolved. It allows programmers to handle and recover from runtime errors gracefully, ensuring that the program does not terminate abruptly.

Exception class is the base class for all exceptions. It is part of the Java standard library and is used as the superclass for all built-in and user-defined exceptions. The Exception class itself extends the Throwable class.




Exception abnormally terminates the execution of the program.

Example:-

public class Example{

statement--1

statement--2

statement--3

statement--4(Exception occurs at line 4)

statement--5

}

In Line no.4 Exception occurs so that statement -5 does not execute.


To handle exceptions use 5 key words.

1. try

2. catch

3. finally

4. throw

5. throws

Exception Handling By using try-catch:


In Java, you can handle exceptions using the try-catch block. The try block contains the code that might throw an exception and the catch the block is responsible for catching and handling the exception. Here's the basic syntax:

java
try
// Code that might throw an exception
} catch (ExceptionType1 exceptionVariable1) { 
// Exception handling code for ExceptionType1 
} catch (ExceptionType2 exceptionVariable2) { 
// Exception handling code for ExceptionType2
finally
// Optional finally block for cleanup code 
}

Let's break down the steps for handling exceptions:

  1. Place the code that might throw an exception within the try block. This is the code where you expect an exceptional condition to occur.

  2. Specify one or more catch blocks immediately after the try block. Each catch block handles a specific type of exception. You need to provide the exception type and assign it to a variable that will hold the exception object.

  3. If an exception occurs within the try block, the corresponding catch block that matches the exception type is executed. The exception object is assigned to the specified variable, allowing you to access information about the exception and perform appropriate error handling.

  4. You can have multiple catch blocks to handle different types of exceptions. The catch blocks are evaluated sequentially, and only the first matching block is executed. You can have a general catch block that catches all types of exceptions by specifying Exception as the exception type.

  5. Optionally, you can include a finally block after the catch block(s). The finally block contains code that is executed regardless of whether an exception occurred or not. It is commonly used for cleanup operations or releasing resources.

Here's an example that demonstrates exception handling:

java
public class ExceptionHandlingExample
public static void main(String[] args)
try {
int result = divide(10, 0);
// Division by zero 
 System.out.println("Result: " + result); 
 } 
catch (ArithmeticException e) {
 System.out.println("An arithmetic exception occurred: " + e.getMessage()); 
 } finally {
 System.out.println("Cleanup code executed.");
 } 
 } 
public static int divide(int num1, int num2)
return num1 / num2;
 } 
}

In this example, the divide method attempts to divide two numbers. However, if the second number is zero, it will throw an ArithmeticException in the try block. The catch block catches this exception, and the appropriate error message is displayed. The finally block is executed regardless of the exception, ensuring that the cleanup code is performed.

By handling exceptions, you can control the flow of your program and provide appropriate error handling for exceptional conditions, preventing the program from crashing and allowing it to recover gracefully.


Type of Exception:

Exceptions are categorized into two types: checked exceptions and unchecked exceptions. These types determine how exceptions are handled by the Java compiler and whether they need to be explicitly handled or declared.

  1. Checked Exceptions: Checked exceptions are exceptions that are checked by the Java compiler at compile-time. If a method throws a checked exception, the caller of that method must handle the exception or declare it in its own throws clause. Examples of checked exceptions in Java include:

    • IOException: Occurs during input/output operations, such as reading from or writing to files.
    • SQLException: Occurs when there are errors in database access or SQL operations.
    • ClassNotFoundException: Occurs when a class is not found at runtime.

    To handle a checked exception, you need to catch it using a try-catch block or declare it in a throws clause.

  2. Unchecked Exceptions: Unchecked exceptions, also known as runtime exceptions, are exceptions that are not checked by the Java compiler at compile-time. They can occur at runtime due to various factors such as programming errors, invalid inputs, or unexpected conditions. Unchecked exceptions do not require explicit handling or declaration. Some common examples of unchecked exceptions in Java include:

    • NullPointerException: Occurs when a null reference is used where an object is expected.
    • ArrayIndexOutOfBoundsException: Occurs when an invalid array index is accessed.
    • IllegalArgumentException: Occurs when an invalid argument is passed to a method.

    Unchecked exceptions are subclasses of the RuntimeException class or its subclasses. These exceptions are not enforced to be caught or declared.

By categorizing exceptions into checked and unchecked types, Java provides a mechanism to distinguish between exceptions that are expected and should be explicitly handled (checked exceptions) and exceptions that indicate programming errors or unexpected conditions (unchecked exceptions). This distinction helps in writing more robust and maintainable code by ensuring that critical exceptions are handled appropriately while allowing the flexibility to handle or propagate runtime exceptions as needed.

throw and throws:

In Java, the throw and throws keywords are used in exception handling, but they serve different purposes:

  1. throw: The throw keyword is used to explicitly throw an exception from a method or block of code. It is followed by an instance of an exception class or a subclass of Throwable. When an exception is thrown, the normal flow of the program is disrupted, and the execution is transferred to an appropriate catch block that can handle the thrown exception.

    Here's an example of using the throw keyword:

    java
    public void checkAge(int age) { if (age < 0) { throw new IllegalArgumentException("Age cannot be negative"); } }

    In this example, the checkAge method throws an IllegalArgumentException if the provided age is negative. The throw keyword is used to create and throw the exception object.

  2. throws: The throws keyword is used in a method declaration to specify that the method may throw one or more types of exceptions. It is used to indicate the potential exceptions that can occur within a method but are not handled within the method itself. The throws clause is followed by a comma-separated list of exception types.

    Here's an example of using the throws keyword:

    java
    public void readFile() throws IOException, FileNotFoundException { // Code that might throw IOException or FileNotFoundException }

    In this example, the readFile method is declared with the throws clause, indicating that it may throw IOException or FileNotFoundException. This informs the caller of the method that they need to handle or propagate these exceptions.

    When a method declares that it throws an exception, it is the responsibility of the calling code to handle the exception using a try-catch block or propagate the exception by declaring it in its own throws clause.

    Additionally, the throws keyword is also used in the declaration of constructors and in method overloading to indicate that the constructor or overloaded method can potentially throw certain exceptions.

Both throw and throws are essential in Java exception handling. The throw keyword is used to explicitly throw exceptions, while the throws keyword is used in method declarations to indicate the exceptions that might be thrown by that method.