Day 11 : Exception Handling in Java

Day 11 : Exception Handling in Java

Exception :

An exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.

Exception Handling :

Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Hierarchy of Java Exception classes :

The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two subclasses: Exception and Error.

Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked. An error is considered as the unchecked exception. According to Oracle, there are three types of exceptions namely:

  • Checked Exception
  • Unchecked Exception
  • Error

Checked Exception :

The classes that directly inherit the Throwable class except RuntimeException and Error are known as checked exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked at compile-time.

Unchecked Exception :

The classes that inherit the RuntimeException are known as unchecked exceptions. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.

Error :

Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError, AssertionError etc.

Java Exception Keywords :

try :

The "try" keyword is used to specify a block where we should place an exception code. It means we can't use try block alone. The try block must be followed by either catch or finally.

catch :

The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be followed by finally block later.

finally :

The "finally" block is used to execute the necessary code of the program. It is executed whether an exception is handled or not.

throw :

The "throw" keyword is used to throw an exception.

throws :

The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception in the method. It doesn't throw an exception. It is always used with method signature.

Some Scenarios of Java Exceptions :

1. A scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

int a=50/0; // ArithmeticException          

2. A scenario where NullPointerException occurs

If we have a null value in any variable, performing any operation on the variable throws a NullPointerException.

String s=null;  
System.out.println(s.length()); // NullPointerException          

3. A scenario where NumberFormatException occurs

If the formatting of any variable or number is mismatched, it may result into NumberFormatException. Suppose we have a string variable that has characters; converting this variable into digit will cause NumberFormatException.

String s="abc";  
int i=Integer.parseInt(s); // NumberFormatException          

4. A scenario where ArrayIndexOutOfBoundsException occurs

When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be other reasons to occur ArrayIndexOutOfBoundsException.

int a[]=new int[5];  
a[10]=50;  // ArrayIndexOutOfBoundsException          

5. A scenario where FileNotFoundException occurs

When the specified file does not exist or cannot be accessed throws a FileNotFoundExeption.

File file = new File("newFile.txt");
FileReader fr = new FileReader(file);  // FileNotFoundException        

Example for ArithmeticException :

  1. Handle ArithmeticException using Try/Catch Block :

import java.lang.ArithmeticException;
public class ArithmeticExceptionHandling {
    public static void main(String[] args) {
        try {
            int divideByZero = 5 / 0;  // Division by zero will throw ArithmeticException
            System.out.println(divideByZero);  // This line won't be reached if exception occurs
        } 
        catch (ArithmeticException e) {
            System.out.println(e);  // Print the exception message
        }
    }
}        

In this example :

try Block :

  • Inside the try block, you have the statement int divideByZero = 5 / 0;.
  • This line attempts to divide 5 by 0, which is not allowed in Java and will result in an ArithmeticException.

catch Block :

  • The catch block catches the ArithmeticException.
  • ArithmeticException e declares a variable e of type ArithmeticException, which represents the exception object thrown.
  • System.out.println(e); prints the exception message using System.out.println(). When you print e, it implicitly calls e.toString(), which returns a string representation of the exception, typically containing the exception class name and the message.

Output :

  • Since division by zero is not allowed, executing this program will result in the ArithmeticException being thrown.
  • The catch block will then handle the exception by printing something like java.lang.ArithmeticException: / by zero.

2. Handle ArithmeticException using Finally Block :

import java.lang.ArithmeticException;
public class ArithmeticExceptionHandling {
    public static void main(String[] args) {
        try {
            int divideByZero = 5 / 0;  // Division by zero will throw ArithmeticException
            System.out.println(divideByZero);  // This line won't be reached if exception occurs
        } 
        catch (ArithmeticException e) {
            System.out.println(e);  // Print the exception message
        } 
        finally {
            System.out.println("This is the finally block");  // Executes regardless of exception
        }
    }
}        

In this example :

try Block :

  • Inside the try block, you have the statement int divideByZero = 5 / 0;.
  • This line attempts to divide 5 by 0, which is not allowed in Java and will result in an ArithmeticException.

catch Block :

  • The catch block catches the ArithmeticException.
  • ArithmeticException e declares a variable e of type ArithmeticException, which represents the exception object thrown.
  • System.out.println(e); prints the exception message using System.out.println(). When you print e, it implicitly calls e.toString(), which returns a string representation of the exception, typically containing the exception class name and the message.

finally Block :

  • The finally block follows the try-catch block.
  • Regardless of whether an exception occurs or not, the code inside the finally block will always execute.
  • In your example, System.out.println("This is the finally block"); prints a message indicating that the finally block is executed.

3. Handle ArithmeticException using throws keyword :

import java.lang.ArithmeticException;
public class ArithmeticExceptionHandling {
    public static void main(String[] args) {
        try {
            int divideByZero = divide(5, 0); // Calling divide method which may throw ArithmeticException
            System.out.println("Result: " + divideByZero);
        } 
        catch (ArithmeticException e) {
            System.out.println(e);
        }
    }

    public static int divide(int dividend, int divisor) throws ArithmeticException {
        return dividend / divisor;
    }
}        

In this example :

main Method :

  • Inside the main method, you have a try-catch block.
  • In the try block, you call the divide method with arguments 5 and 0. This is an intentional setup to cause an ArithmeticException because dividing by zero is not allowed in Java.

divide Method :

  • The divide method is declared with throws ArithmeticException in its signature. This indicates that the method can throw an ArithmeticException during its execution.
  • In this case, if divisor is 0, the method will indeed throw an ArithmeticException.

Handling the Exception:

  • If an ArithmeticException is thrown within the divide method, it is caught by the catch (ArithmeticException e) block in the main method.
  • The exception message (e.toString()) is then printed using System.out.println("Exception caught in main method: " + e);.

4. Handle ArithmeticException using throw Keyword :

import java.lang.ArithmeticException;
public class ArithmeticExceptionHandling {
    public static void main(String[] args) {
        try {
            int divideByZero = divide(5, 0); // Calling divide method which may throw ArithmeticException
            System.out.println("Result : " + divideByZero);
        } 
        catch (ArithmeticException e) {
            System.out.println(e);
        }
    }

    public static int divide(int dividend, int divisor) {
        if (divisor == 0) {
            throw new ArithmeticException("Division by zero is not allowed");
        }
        return dividend / divisor;
    }
}        

Example for NullPointerException :

  1. Handle NullPointerException using try / catch block :

public class NullPointerExceptionHandling {
    public static void main(String[] args) {
        try {
            String str = null;
            System.out.println("Length of the string: " + str.length()); // This line will throw NullPointerException
        } 
        catch (NullPointerException e) {
            System.out.println(e); // Print the exception
        }
    }
}        

In this example :

try Block :

  • String str = null; initializes str to null, meaning it does not refer to any object.
  • str.length() attempts to access the length() method of str, which is null. This operation throws a NullPointerException.

catch Block :

  • The catch (NullPointerException e) block catches the NullPointerException when it occurs.
  • System.out.println(e); prints the exception object e. In Java, printing an exception object (e) implicitly calls its toString() method, which typically prints the exception type and message.

2. Handle NullPointerException using finally block :

public class NullPointerExceptionHandling {
    public static void main(String[] args) {
        try {
            String str = null;
            System.out.println("Length of the string: " + str.length()); // This line will throw NullPointerException
        } 
        catch (NullPointerException e) {
            System.out.println(e); // Print the exception
        }
        finally {
            System.out.println("This is the finally block");  // Executes regardless of exception
        }
    }
}        

In this example :

try Block :

  • String str = null; initializes str to null, meaning it does not refer to any object.
  • str.length() attempts to access the length() method of str, which is null. This operation throws a NullPointerException.

catch Block :

  • The catch (NullPointerException e) block catches the NullPointerException when it occurs.
  • System.out.println(e); prints the exception object e. In Java, printing an exception object implicitly calls its toString() method, which typically prints the exception type and message.

finally Block :

  • The finally block is executed regardless of whether an exception is thrown or caught. Its purpose is to ensure that certain cleanup or finalization tasks are performed, such as closing resources or releasing locks.

3. Handle NullPointerException using throws keyword :

public class NullPointerExceptionHandling {
    public static void main(String[] args) {
        try {
            String str = null;
            printStringLength(str); // Calling method that may throw NullPointerException
        } 
        catch (NullPointerException e) {
            System.out.println(e);
        }
    }
    public static void printStringLength(String str) throws NullPointerException {
        if (str == null) {
            throw new NullPointerException("String is null"); // Throw NullPointerException explicitly
        }
        System.out.println("Length of the string: " + str.length());
    }
}        

In this example :

main Method :

  • Inside main, String str = null; initializes str to null.
  • printStringLength(str); calls the printStringLength method with str as an argument, which may throw NullPointerException.

printStringLength Method :

  • printStringLength(String str) throws NullPointerException { ... } declares that this method may throw NullPointerException.
  • Before accessing str.length(), the method checks if str is null.
  • If str is null, throw new NullPointerException("String is null"); explicitly throws NullPointerException with a custom error message.
  • If str is not null, it proceeds to print the length of the string using str.length().

try-catch Block :

  • The try block in main attempts to call printStringLength(str);.
  • If printStringLength throws NullPointerException, it is caught in the catch block, where System.out.println(e); prints the exception (e).

4. Handle NullPointerException using throw keyword :

public class NullPointerExceptionHandling {
    public static void main(String[] args) {
        try {
            String str = null;
            printStringLength(str); // Calling method that may throw NullPointerException
        } 
        catch (NullPointerException e) {
            System.out.println(e);
        }
    }
    public static void printStringLength(String str) {
        if (str == null) {
            throw new NullPointerException("String is null"); // Throw NullPointerException explicitly
        }
        System.out.println("Length of the string: " + str.length());
    }
}        

In this example :

main Method :

  • Inside main, String str = null; initializes str to null.
  • printStringLength(str); calls the printStringLength method with str as an argument, which may throw NullPointerException.

printStringLength Method :

  • printStringLength(String str) does not have a throws clause, meaning it does not declare that it throws NullPointerException.
  • Inside printStringLength, before accessing str.length(), the method explicitly checks if str is null.
  • If str is null, throw new NullPointerException("String is null"); explicitly throws NullPointerException with a custom error message.
  • If str is not null, it proceeds to print the length of the string using str.length().

try-catch Block :

  • The try block in main attempts to call printStringLength(str);.
  • If printStringLength throws NullPointerException, it is caught in the catch block, where System.out.println(e); prints the exception (e).

Example for NumberFormatException :

  1. Handle NumberFormatException using try / catch block :

public class NumberFormatExceptionHandling {
    public static void main(String[] args) {
        String s = "abc"; // Invalid numeric string
        try {
            int num = Integer.parseInt(s); // Attempting to parse string to integer
            System.out.println(num);
        } 
        catch (NumberFormatException e) {
            System.out.println(e);
        }
    }
}        

In this example :

main Method :

  • String s = "abc"; initializes s with a string "abc", which is not a valid numeric format.

try Block :

  • int num = Integer.parseInt(s); attempts to parse s into an int. This operation may throw NumberFormatException if s is not a valid integer format.

catch Block :

  • The catch (NumberFormatException e) block catches NumberFormatException if it occurs during the parsing operation.
  • System.out.println(e); prints the exception (e). In Java, printing an exception object implicitly calls its toString() method, which typically prints the exception type and message.

2. Handle NumberFormatException using finally block :

public class NumberFormatExceptionHandling {
    public static void main(String[] args) {
        String s = "abc"; // Invalid numeric string
        try {
            int num = Integer.parseInt(s); // Attempting to parse string to integer
            System.out.println(num);
        } 
        catch (NumberFormatException e) {
            System.out.println(e);
        } finally {
            System.out.println("This is finally block"); // Executes regardless of exception
        }
    }
}        

In this example :

main Method :

  • String s = "abc"; initializes s with a string "abc", which is not a valid numeric format.

try Block :

  • int num = Integer.parseInt(s); attempts to parse s into an int. This operation may throw NumberFormatException if s is not a valid integer format.
  • System.out.println(num); prints the parsed integer if successful.

catch Block:

  • The catch (NumberFormatException e) block catches NumberFormatException if it occurs during the parsing operation.
  • System.out.println(e); prints the exception (e). In Java, printing an exception object implicitly calls its toString() method, which typically prints the exception type and message.

finally Block :

  • The finally block is executed regardless of whether an exception is thrown or caught.
  • System.out.println("This is finally block"); prints a message indicating execution inside the finally block.

3. Handle NumberFormatException using throws keyword :

public class NumberFormatExceptionHandling {
    public static void main(String[] args) {
        String s = "abc"; // Invalid numeric string
        try {
            int num = parseInteger(s); // Calling method that may throw NumberFormatException
            System.out.println(num);
        } 
        catch (NumberFormatException e) {
            System.out.println(e); // Print the exception
        }
    }
    public static int parseInteger(String s) throws NumberFormatException {
        return Integer.parseInt(s); // Attempting to parse string to integer
    }
}        

In this example :

main Method :

  • String s = "abc"; initializes s with a string "abc", which is not a valid numeric format.

try Block :

  • int num = parseInteger(s); calls the parseInteger method with s as an argument. This method may throw NumberFormatException if s is not a valid integer format.
  • System.out.println(num); prints the parsed integer if successful.

catch Block :

  • The catch (NumberFormatException e) block catches NumberFormatException if it occurs during the parsing operation.
  • System.out.println(e); prints the exception (e). In Java, printing an exception object implicitly calls its toString() method, which typically prints the exception type and message.

parseInteger Method :

  • public static int parseInteger(String s) throws NumberFormatException { ... } declares that this method can throw NumberFormatException.
  • Inside parseInteger, Integer.parseInt(s); attempts to parse s into an int. If s is not a valid integer format, NumberFormatException is thrown.

4. Handle NumberFormatException using throw keyword :

public class NumberFormatExceptionHandling {
    public static void main(String[] args) {
        String s = "abc"; // Invalid numeric string
        try {
            int num = parseInteger(s); // Calling method that may throw NumberFormatException
            System.out.println(num);
        } 
        catch (NumberFormatException e) {
            System.out.println(e);
        }
    }    
    public static int parseInteger(String s) throws NumberFormatException {
        if (s == null || s.isEmpty()) {
            throw new NumberFormatException("Input string is null or empty");
        }
        int result;
        try {
            result = Integer.parseInt(s); // Attempting to parse string to integer
        } 
        catch (NumberFormatException e) {
            throw new NumberFormatException("Failed to parse integer: " + s);
        }   
        return result;
    }
}        

In this example :

main Method :

  • String s = "abc"; initializes s with a string "abc", which is not a valid numeric format.

try Block :

  • int num = parseInteger(s); calls the parseInteger method with s as an argument. This method may throw NumberFormatException if s is not a valid integer format.
  • System.out.println(num); prints the parsed integer if successful.

catch Block :

  • The catch (NumberFormatException e) block catches NumberFormatException if it occurs during the parsing operation.
  • System.out.println(e); prints the exception (e). In Java, printing an exception object implicitly calls its toString() method, which typically prints the exception type and message.

parseInteger Method :

  • public static int parseInteger(String s) throws NumberFormatException { ... } declares that this method can throw NumberFormatException.
  • Checks if s is null or empty. If so, it throws NumberFormatException with a specific message (throw new NumberFormatException("Input string is null or empty");).
  • Attempts to parse s into an int using Integer.parseInt(s);. If parsing fails (e.g., due to invalid format), it catches NumberFormatException and throws a new NumberFormatException with a customized error message (throw new NumberFormatException("Failed to parse integer: " + s);).

Example for ArrayIndexOutOfBoundException :

  1. Handle ArrayIndexOutOfBoundException using try / catch block :

public class ArrayIndexOutOfBoundsExceptionHandling {
    public static void main(String[] args) {
        try {
            int[] num = {5, 10, 20, 25, 50};
            System.out.println(num[10]); // Trying to access an element outside the bounds of the array
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println(e); // Print the exception
        }
    }
}        

In this example :

try Block :

  • int[] num = {5, 10, 20, 25, 50}; initializes an array num with 5 elements.
  • System.out.println(num[10]); attempts to access the element at index 10 in the array num. Since arrays in Java are zero-indexed and num has only 5 elements (indices 0 to 4), accessing index 10 will cause ArrayIndexOutOfBoundsException.
  • The code that may potentially throw ArrayIndexOutOfBoundsException is enclosed in the try block (System.out.println(num[10]);).

catch Block :

  • The catch (ArrayIndexOutOfBoundsException e) block catches ArrayIndexOutOfBoundsException if it occurs during the array access operation.
  • System.out.println(e); prints the exception (e). In Java, printing an exception object implicitly calls its toString() method, which typically prints the exception type and message.

2. Handle ArrayIndexOutOfBoundException using finally block :

public class ArrayIndexOutOfBoundsExceptionHandling {
    public static void main(String[] args) {
        try {
            int[] num = {5, 10, 20, 25, 50};
            System.out.println(num[10]); // Trying to access an element outside the bounds of the array
        } 
        catch (ArrayIndexOutOfBoundsException e) {
            System.out.println(e); // Print the exception
        } 
        finally {
            System.out.println("Finally block executed"); // Executes regardless of whether an exception occurred or not
        }
    }
}        

try Block :

  • int[] num = {5, 10, 20, 25, 50}; initializes an array num with 5 elements.
  • System.out.println(num[10]); attempts to access the element at index 10 in the array num. Since num has only indices from 0 to 4, accessing index 10 will throw ArrayIndexOutOfBoundsException.
  • The code that may potentially throw ArrayIndexOutOfBoundsException is enclosed in the try block (System.out.println(num[10]);).

catch Block :

  • The catch (ArrayIndexOutOfBoundsException e) block catches ArrayIndexOutOfBoundsException if it occurs during the array access operation.
  • System.out.println(e); prints the exception (e). In Java, printing an exception object implicitly calls its toString() method, which typically prints the exception type and message.

finally Block :

  • The finally block (finally { }) is used to execute cleanup or finalization code that should run regardless of whether an exception occurred or not.
  • System.out.println("Finally block executed"); is executed after the try or catch block, providing a mechanism for cleanup operations.

3. Handle ArrayIndexOutOfBoundException using throws keyword :

public class ArrayIndexOutOfBoundsExceptionHandling {
    public static void main(String[] args) {
        try {
            int[] num = {5, 10, 20, 25, 50};
            getElement(num, 10); // Calling method that may throw ArrayIndexOutOfBoundsException
        } 
        catch (ArrayIndexOutOfBoundsException e) {
            System.out.println(e); // Print the exception
        }
    }
    public static int getElement(int[] array, int index) throws ArrayIndexOutOfBoundsException {
        return array[index]; // Accessing array element which may throw ArrayIndexOutOfBoundsException
    }
}        

In this example :

try Block :

  • int[] num = {5, 10, 20, 25, 50}; initializes an array num with 5 elements.
  • getElement(num, 10); calls the getElement method with num array and 10 as the index argument. This method may throw ArrayIndexOutOfBoundsException if the index 10 is out of bounds for the num array.
  • The code that may potentially throw ArrayIndexOutOfBoundsException is enclosed in the try block (getElement(num, 10);).

catch Block :

  • The catch (ArrayIndexOutOfBoundsException e) block catches ArrayIndexOutOfBoundsException if it occurs during the array access operation.
  • System.out.println(e); prints the exception (e). In Java, printing an exception object implicitly calls its toString() method, which typically prints the exception type and message.

getElement Method :

  • public static int getElement(int[] array, int index) throws ArrayIndexOutOfBoundsException { ... } declares that this method can throw ArrayIndexOutOfBoundsException.
  • Accesses array[index] which may throw ArrayIndexOutOfBoundsException if index is out of bounds for the array array.

4. Handle ArrayIndexOutOfBoundException using throw keyword :

public class ArrayIndexOutOfBoundsExceptionHandling {
    public static void main(String[] args) {
        try {
            int[] num = {5, 10, 20, 25, 50};
            getElement(num, 10); // Calling method that may throw ArrayIndexOutOfBoundsException
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println(e); // Print the exception
        }
    }
    public static int getElement(int[] array, int index) {
        if (index < 0 || index >= array.length) {
            throw new ArrayIndexOutOfBoundsException("Index " + index + " is out of bounds for array of length " + array.length);
        }
        return array[index]; // Accessing array element which may throw ArrayIndexOutOfBoundsException
    }
}        

In this example :

try Block :

  • int[] num = {5, 10, 20, 25, 50}; initializes an array num with 5 elements.
  • getElement(num, 10); calls the getElement method with num array and 10 as the index argument. This method may throw ArrayIndexOutOfBoundsException if the index 10 is out of bounds for the num array.
  • The code that may potentially throw ArrayIndexOutOfBoundsException is not explicitly surrounded by a try block here, as the exception is thrown directly within the getElement method.

catch Block :

  • The catch (ArrayIndexOutOfBoundsException e) block catches ArrayIndexOutOfBoundsException if it occurs during the array access operation.
  • System.out.println(e); prints the exception (e). In Java, printing an exception object implicitly calls its toString() method, which typically prints the exception type and message.

getElement Method :

  • public static int getElement(int[] array, int index) { ... } does not declare throws ArrayIndexOutOfBoundsException, as the exception is thrown explicitly within the method.
  • Checks if index is within the bounds of the array (if (index < 0 || index >= array.length)).
  • If index is out of bounds, throws new ArrayIndexOutOfBoundsException("Index " + index + " is out of bounds for array of length " + array.length).

Example for FileNotFoundException :

  1. Handle FileNotFoundException using try / catch block :

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class FileNotFoundExceptionHandling {
	public static void main(String[] args) {
		try {
			File newFile = new File("newFile.txt");
		    FileInputStream stream = new FileInputStream(newFile); 
		}
		catch(FileNotFoundException e) {
			System.out.println(e);
		}
	}
}        

In this example :

try Block :

  • File newFile = new File("newFile.txt"); creates a File object representing a file named "newFile.txt". This file is assumed to be in the current working directory.
  • FileInputStream stream = new FileInputStream(newFile); attempts to create a FileInputStream object to read from newFile. If newFile does not exist or cannot be opened for reading, it throws a FileNotFoundException.
  • The code that may potentially throw FileNotFoundException is enclosed in the try block (new FileInputStream(newFile)).

catch Block :

  • The catch (FileNotFoundException e) block catches FileNotFoundException if it occurs during the attempt to open the file.
  • System.out.println(e); prints the exception (e). In Java, printing an exception object implicitly calls its toString() method, which typically prints the exception type and message.

2. Handle FileNotFoundException using finally block :

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class FileNotFoundExceptionHandling {
    public static void main(String[] args) {
        try {
            File newFile = new File("newFile.txt");
            FileInputStream stream = new FileInputStream(newFile);
        } 
        catch(FileNotFoundException e) {
            System.out.println(e); // Print the exception
        } 
        finally {
            System.out.println("This is finally block"); // Executes regardless of whether an exception occurred or not
        }
    }
}        

In this example :

try Block :

  • File newFile = new File("newFile.txt"); creates a File object representing a file named "newFile.txt" in the current working directory.
  • FileInputStream stream = new FileInputStream(newFile); attempts to create a FileInputStream object to read from newFile. If newFile does not exist or cannot be opened for reading, it throws a FileNotFoundException.
  • The code that may potentially throw FileNotFoundException is enclosed in the try block (new FileInputStream(newFile)).

catch Block :

  • The catch (FileNotFoundException e) block catches FileNotFoundException if it occurs during the attempt to open the file.
  • System.out.println(e); prints the exception (e). In Java, printing an exception object implicitly calls its toString() method, which typically prints the exception type and message.

finally Block :

  • The finally block is used to execute code that needs to run regardless of whether an exception occurred or not.
  • System.out.println("This is finally block"); prints a message indicating that the finally block executed. This demonstrates that the finally block is reached after either the try block or the catch block completes, ensuring cleanup or finalization tasks.

3. Handle FileNotFoundException using throws keyword :

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class FileNotFoundExceptionHandling {
    public static void main(String[] args) {
        try {
            openFile("newFile.txt");
        } 
        catch (FileNotFoundException e) {
            System.out.println(e); // Print the exception
        }
    }
    public static void openFile(String filename) throws FileNotFoundException {
        File newFile = new File(filename);
        FileInputStream stream = new FileInputStream(newFile);
        System.out.println("File opened successfully: " + newFile.getName());
    }
}        

In this example :

main Method :

  • try block calls the openFile method with "newFile.txt" as the filename argument. The openFile method may throw FileNotFoundException.

openFile Method :

  • public static void openFile(String filename) throws FileNotFoundException { ... } declares that this method may throw FileNotFoundException.
  • File newFile = new File(filename); creates a File object representing a file with the specified filename.
  • FileInputStream stream = new FileInputStream(newFile); attempts to create a FileInputStream object to read from newFile. If newFile does not exist or cannot be opened for reading, it throws a FileNotFoundException.
  • System.out.println("File opened successfully: " + newFile.getName()); prints a message indicating that the file was opened successfully if no exception is thrown.

throws Keyword :

  • throws FileNotFoundException in the method signature of openFile indicates that this method may throw FileNotFoundException. This informs the caller (main method in this case) that it should handle this exception or propagate it further up the call stack.

4. Handle FileNotFoundException using throw keyword :

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class FileNotFoundExceptionHandling {
    public static void main(String[] args) {
        try {
            openFile("newFile.txt"); // Attempting to open a file named "newFile.txt"
        } catch (FileNotFoundException e) {
            System.out.println(e);
        }
    } 
    public static void openFile(String filename) throws FileNotFoundException {
        File newFile = new File(filename); // Creating a File object with the specified filename     
        if (!newFile.exists()) {
            throw new FileNotFoundException("File '" + filename + "' not found"); // Throw FileNotFoundException explicitly
        }      
        FileInputStream stream = new FileInputStream(newFile); // Attempting to create a FileInputStream
        System.out.println("File opened successfully: " + newFile.getName());
    }
}        

In this example :

main Method :

  • try block calls the openFile method with "newFile.txt" as the filename argument. The openFile method may throw FileNotFoundException.

openFile Method :

  • public static void openFile(String filename) throws FileNotFoundException { ... } declares that this method may throw FileNotFoundException.
  • File newFile = new File(filename); creates a File object representing a file with the specified filename.
  • if (!newFile.exists()) { throw new FileNotFoundException("File '" + filename + "' not found"); } checks if the file exists. If not, it explicitly throws FileNotFoundException with a custom error message.
  • FileInputStream stream = new FileInputStream(newFile); attempts to create a FileInputStream object to read from newFile. If newFile does not exist or cannot be opened for reading, it throws a FileNotFoundException.
  • System.out.println("File opened successfully: " + newFile.getName()); prints a message indicating that the file was opened successfully if no exception is thrown.

要查看或添加评论,请登录

POOJAASHREE P V的更多文章

  • Day 13 : File Handling in Java

    Day 13 : File Handling in Java

    File Class : The File class of the java.io package is used to perform various operations on files and directories.

  • Day 12 : Scanner Class in Java

    Day 12 : Scanner Class in Java

    Scanner Class : Scanner class in Java is found in the java.util package.

  • Day 10 : Arrays in Java

    Day 10 : Arrays in Java

    Arrays : Array is an object which contains elements of a similar data type. The elements of an array are stored in a…

  • Day 9 : Date and Time in Java

    Day 9 : Date and Time in Java

    Date and Time : In Java, managing date and time involves several classes from the package, introduced in Java 8. The…

  • Day 8 : String, String Methods, String Builder and String Buffer in Java

    Day 8 : String, String Methods, String Builder and String Buffer in Java

    String : String is an object that represents a sequence of characters. The java.

  • Day 7 : Math Class and Math Methods in Java

    Day 7 : Math Class and Math Methods in Java

    Math Class : Math class provides several methods to work on math calculations like min(), max(), avg(), sin(), cos()…

  • Day 6 : Methods in Java

    Day 6 : Methods in Java

    Method : A method is a block of code or collection of statements or a set of code grouped together to perform a certain…

  • Day 5 : Looping Statements in Java

    Day 5 : Looping Statements in Java

    Looping Statements : Looping statements are used to execute a block of code repeatedly based on certain conditions…

    1 条评论
  • Day 4 : Conditional Statements in Java

    Day 4 : Conditional Statements in Java

    Conditional Statements : Conditional statements are control flow statements that allow you to execute different blocks…

  • Day 3 : Variables, Data Types and Operators

    Day 3 : Variables, Data Types and Operators

    Variables : A variable is a container which holds the value while the Java program is executed. A variable is assigned…

社区洞察

其他会员也浏览了