java

Java Exception Handling


What is exception?

An exception is unexpected/unwanted/abnormal situation that occurs at runtime called exception.

Real-life example:

1. PowerCutException - Suppose you are working in computer and you forgot to save your files/folders then suddenly power-cut .

2. SickException - Suppose you are going on a trip and you get fever, in such a situation if you had taken some medicine then perhaps you could have recovered.

 

What is Exception Handling?

Exception handling in Java is a mechanism that allows you to deal with errors and unexpected situations that may occur during the execution of a program. So we should have an alternate source to handle these exception.

 

Note:

1. In Java, exceptions are objects that represent errors or exceptional conditions.

2. When an error or exceptional condition occurs, an exception object is thrown, and the normal flow of the program is disrupted.

 


In Java, many pre-defined exceptions provided by the language.

1. ArithmeticException: Thrown when an exceptional arithmetic condition has occurred, such as division by zero.

2.  ArrayIndexOutOfBoundsException: Thrown to indicate that an array has been accessed with an illegal index.

3.  NullPointerException: Thrown when an application attempts to access or modify an object with a null reference.

4.  FileNotFoundException: Thrown when an attempt to open the file denoted by a specified pathname fails.

5.  IOException: The general class of exceptions produced by failed or interrupted I/O operations.

6. ClassNotFoundException: Thrown when an application tries to load a class but the specified class cannot be found.

 

The object oriented programming provides the following techniques to work with exception:

 

  • try: Whenever we write a statement and if the statement is error suspecting statement or risky-code then put that code inside the try-block.

Syntax:

try {
    // Code that may cause an exception
} catch (ExceptionType1 ex1) {
    // Handle exception of type ExceptionType1
} catch (ExceptionType2 ex2) {
    // Handle exception of type ExceptionType2
} catch (Exception ex) {
    // Handle any other type of exception
}

 

Note: 

catch (Exception ex) {
    // Handle any other type of exception
}

What is this Exception in above code? 

1. It is a super class of all exceptions like ArithmeticException,  ClassNotFoundException etc… 

2. Always try to use it at  last of catch block because  if you suppose there is such an exception which can handle the particular exception like “divide by zero” then ArithmeticException will handle this , then if all the exceptions are checked and not handled, then finally this exception class is handled.

 

Example:

public class DivideByZeroExample {
    public static void main(String[] args) {
        // Some code that may cause a divide by zero exception
        int numerator = 10;
        int denominator = 0;

        try {
            int result = numerator / denominator;
            System.out.println("Result of division: " + result);
        } catch (ArithmeticException e) {
            // Handle the divide by zero exception
            System.err.println("Error: Division by zero is not allowed.");
        }
    }
}

 

Output:

Error: Division by zero is not allowed.
java.lang.ArithmeticException: / by zero
	at DivideByZeroExample.main(DivideByZeroExample.java:10)

 

 

  • catch: Each catch block is responsible for catching and handling a specific type of exception.

 

Syntax:

try {
    // Code that may cause an exception
} catch (ExceptionType1 ex1) {
    // Handle exception of type ExceptionType1
} catch (ExceptionType2 ex2) {
    // Handle exception of type ExceptionType2
} catch (Exception ex) {
    // Handle any other type of exception
}

 

Example:

class NumberFormatExceptionExample {
    public static void main(String[] args) {
        // Some code that may cause a NumberFormatException
        String invalidNumber = "abc";

        try {
            // Attempt to convert the string to an integer
            int convertedNumber = Integer.parseInt(invalidNumber);
            System.out.println("Converted number: " + convertedNumber);
        } catch (NumberFormatException e) {
            // Handle the NumberFormatException
            System.err.println("Error: Invalid number format. Please enter a valid numeric value.");
        }
    }
}

 

Output:

Error: Invalid number format. Please enter a valid numeric value.
java.lang.NumberFormatException: For input string: "abc"
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
    at java.base/java.lang.Integer.parseInt(Integer.java:662)
    at java.base/java.lang.Integer.parseInt(Integer.java:770)
    at NumberFormatExceptionExample.main(NumberFormatExceptionExample.java:9)

Note:  You can have multiple catch blocks to handle different types of exceptions that may occur within the try block.

 

  • finally: 

1. It is used to define a block of code that will be executed regardless of whether an exception is thrown or not. 

2. The finally block is often used for cleanup or resource release tasks, ensuring that certain operations are performed regardless of the outcome of the try and catch blocks.

Syntax:

try {
    // Code that may cause an exception
} catch (ExceptionType e) {
    // Code to handle the exception
} finally {
    // Code that will be executed regardless of whether an exception occurs or not
}

 

Example:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

class FileReadExample {

    public static void main(String[] args) {
        // Specify the file path
        String filePath = "example.txt";
        BufferedReader reader = null;

        try {
            // Open a file for reading
            reader = new BufferedReader(new FileReader(filePath));

            // Read data from the file (this could potentially throw an IOException)
            String line = reader.readLine();
            System.out.println("Read from file: " + line);

		} catch (IOException e) {
            // Handle IOException (e.g., log the exception or take appropriate action)
            System.err.println("IOException: " + e.getMessage());
        } finally {
            try {
                // Close the file in the finally block to ensure it is always closed
                if (reader != null) {
                    reader.close();
                    System.out.println("File closed successfully.");
                }
            } catch (IOException e) {
                // Handle IOException during the closing of the file
                System.err.println("Error closing file: " + e.getMessage());
            }
        }
    }
}

 

Note:

  • The finally block contains code that must be executed regardless of whether an exception occurred in the try block or not.
  • In this example, the finally block is used to close the file (BufferedReader) to ensure that resources are released properly.
  • Closing the file in the finally block is crucial because it guarantees that the file will be closed, even if an exception occurs in the try block. This is essential for resource cleanup and preventing resource leaks.

 

  • throw: The throw keyword is used to explicitly throw an exception. You can throw exceptions based on certain conditions in your code.

 

Example:

public class ExceptionHandlingExample {
    public static void main(String[] args) {
        try {
            // Code that may cause an exception
            int result = divide(10, 0);
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            // Catching and handling the specific exception
            System.out.println("Error: " + e.getMessage());
        } finally {
            // Code in the finally block is executed regardless of whether an exception occurred or not
            System.out.println("This will always be executed.");
        }
    }

    // A method that throws an exception
    public static int divide(int a, int b) {
        if (b == 0) {
            throw new ArithmeticException("Cannot divide by zero");
        }
        return a / b;
    }
}

 

Output:

Error: Cannot divide by zero
This will always be executed.

 

  • throws: The throws keyword is used in method declarations to indicate that a particular method might throw exceptions of a specified type. This is part of the method signature.

 

Syntax:

return_type method_name() throws exception_class_name {  
//method code  
} 

Example:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class FileReaderExample {
    public static void main(String[] args) {
        try {
            // Call a method that reads data from a file
            readDataFromFile("example.txt");
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("IOException: " + e.getMessage());  // The getMessage() method prints only the description of the exception.
        }
    }

    // A method that declares it may throw FileNotFoundException and IOException using throws
    public static void readDataFromFile(String fileName) throws FileNotFoundException, IOException {
        BufferedReader reader = null;
        try {
            // Attempt to read from the file
            reader = new BufferedReader(new FileReader(fileName));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } finally {
            // Close the file reader in the finally block to ensure proper cleanup
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    System.out.println("Error closing the file: " + e.getMessage());
                }
            }
        }
    }
}

 

Output:

1. If the file "example.txt" exists:

Line 1
Line 2
Line 3

 

2. If the file "example.txt" does not exist:

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

 

Note: Checked exception only, we can declare using throws