Posted in

EXCEPTIONS PROGRAMS AND ALGORITHMS IN JAVA

1. Write a program to what happens if an exception is not caught in Java?

Algorithm :

  •  Start Execution:
    • The program begins executing from the main method.
  • Call to method1():
    • Inside main, the method1() method is invoked.
  • Call to method2():
    • Inside method1(), the method2() method is invoked.
  • Execute Division in method2():
    • In method2(), the line int result = 10 / 0; is executed, which attempts to divide 10 by 0.
  •  Exception Occurs:
    • A java.lang.ArithmeticException is thrown due to division by zero.
  •  Exception Propagation:
    • Since method2() does not handle the exception, it is propagated up to method1().
    • method1() also does not handle the exception, so it is propagated further up to the main method.
  •  Program Terminates:
    • As the exception is unhandled in all methods, the Java Virtual Machine (JVM) terminates the program abnormally and prints a stack trace.
  • End

Program :

  public class ExceptionExample {
    public static void main(String[] args) {
        method1();
    }
    static void method1() {
        method2();
    }
    static void method2() {
        int result = 10 / 0;  // Divide by zero
    }
}

Output :

Exception in thread “main” java.lang.ArithmeticException: / by zero
  at ExceptionExample.method2(ExceptionExample.java:9)
  at ExceptionExample.method1(ExceptionExample.java:6)
  at ExceptionExample.main(ExceptionExample.java:3)

Explanation :

The execution of the program begins in the main method, where the method1() is called. This method, in turn, calls method2(). Inside method2(), the statement int result = 10 / 0; attempts to divide an integer by zero. Since division by zero is not allowed in Java, this results in a runtime exception of type ArithmeticException. Because this exception is not caught within method2(), it propagates back to the calling method method1(), and then further up to main(). As none of these methods handle the exception using a try-catch block, the Java Virtual Machine (JVM) terminates the program and prints an error message along with a stack trace, indicating the location and type of the error.

2. Write a program to what is the difference between throws and throw in Java?

Algorithm :

  • Start
  • Class Definition:
    • A custom exception class MyException is defined by extending the Exception class. It includes a constructor that takes a message and passes it to the superclass constructor.
  • Main Program Start:
    • Execution begins with the main method.
  • Try Block Begins:
    • Inside the main method, a try block is used to wrap a call to myMethod().
  • Call to myMethod():
    • The method myMethod() is called from within the try block.
  • Throwing the Exception:
    • Inside myMethod(), the throw keyword is used to explicitly throw a new instance of MyException with the message “This is a thrown exception”.
  • Exception Propagation:
    • Because myMethod() throws a checked exception, and it is declared with throws MyException, the exception is passed to the calling method (main).
  • Exception Caught:
    • The catch block in main catches the MyException, and its message is printed to the console:
      Caught exception: This is a thrown exception
  • End

Program :

class MyException extends Exception {
    public MyException(String message) {
        super(message);
    }
}
public class ThrowThrowsExample {
    public static void myMethod() throws MyException {
        throw new MyException(“This is a thrown exception”);
    }
    public static void main(String[] args) {
        try {
            myMethod(); 
        } catch (MyException e) {
            System.out.println(“Caught exception: ” + e.getMessage());
        }
    }
}

Output :

Caught exception: This is a thrown exception

Explanation :

         This program demonstrates the use of both throw and throws in Java for handling custom checked exceptions. A custom exception class MyException is defined by extending the base Exception class. In the myMethod(), the throw keyword is used to explicitly create and throw an instance of this custom exception. Since this is a checked exception, the method must declare it using the throws clause in its signature. In the main method, a call to myMethod() is placed within a try block to handle any potential exceptions it might throw. When myMethod() executes and throws the exception, control is transferred to the catch block in main, which catches the MyException and prints out its message. This illustrates a clean and structured way to define and handle custom exceptions in Java using throw and throws.

3. Write a program to how do you handle multiple exceptions in a single catch block?

Algorithm :

  • Start the program and enter the main method.
  • Enter the try block to execute the code that may throw exceptions.
  • Execute the division int result = 10 / 0;, which causes an ArithmeticException due to division by zero.
  • Immediately jump to the catch block because an exception occurred; skip the remaining code in the try block.
  •   Handle the exception in the multi-catch block: print “Caught exception: ” followed by the exception object.
  •  Exit the catch block and
  •  End the program.

Program :

public class MultipleExceptionsExample {
    public static void main(String[] args) {
        try {
            // Simulate an ArithmeticException
            int result = 10 / 0;  // Division by zero
            // Simulate a NullPointerException
            String str = null;
            str.length();  // Attempt to call method on null object
        } catch (ArithmeticException | NullPointerException e) {
            System.out.println(“Caught exception: ” + e);
        }
    }
}

Output :

Caught exception: java.lang.ArithmeticException: / by zero

Explanation :

          In this program, multiple potential exceptions are handled using a single multi-catch block. Execution begins in the main method, where the program enters a try block that simulates two exceptions. The first line performs an illegal division by zero, which immediately throws an ArithmeticException. As soon as this exception occurs, the execution of the remaining code in the try block is aborted, and control is transferred to the catch block. The multi-catch block is capable of handling both ArithmeticException and NullPointerException, and in this case, it catches the ArithmeticException. The corresponding error message is printed to the console. The second potential exception, a NullPointerException, is never reached because the first exception interrupts the flow.

4. Write a program for checked exception and unchecked exception?

Algorithm :

  • Start :
  • First try Block Begins:
    • The program attempts to execute readFile() inside a try block.
  • Checked Exception Thrown:
    • readFile() throws a FileNotFoundException using throw new FileNotFoundException(“File not found!”).
  • Checked Exception Caught:
    • The exception is caught by the corresponding catch block, and the message
      “Checked Exception Caught: java.io.FileNotFoundException: File not found!” is printed.
  • Second try Block Begins:
    • The program proceeds to the next try block and calls divideByZero().
  • Unchecked Exception Thrown:
    • Inside divideByZero(), the statement int result = 10 / 0; causes an ArithmeticException due to division by zero.
  • Unchecked Exception Caught:
    • The exception is caught by the corresponding catch block, and the message
      “Unchecked Exception Caught: java.lang.ArithmeticException: / by zero” is printed.
  • End :
    • After handling both exceptions, the program completes successfully without crashing.

Program :

 public class ExceptionExample {
    public static void readFile() throws java.io.FileNotFoundException {
        throw new java.io.FileNotFoundException(“File not found!”);
    }
    public static void divideByZero() {
        int result = 10 / 0; 
    }
    public static void main(String[] args) {
        try {
            readFile(); 
        } catch (java.io.FileNotFoundException e) {
            System.out.println(“Checked Exception Caught: ” + e);
        }
        try {
            divideByZero();
        } catch (ArithmeticException e) {
            System.out.println(“Unchecked Exception Caught: ” + e);
        }
    }
}

Output :

Checked Exception Caught: java.io.FileNotFoundException: File not found!
Unchecked Exception Caught: java.lang.ArithmeticException: / by zero

Explanation :

        This Java program illustrates how to handle both checked and unchecked exceptions using try-catch blocks. It begins by calling the readFile() method, which is designed to throw a checked exception (FileNotFoundException). Because checked exceptions must be either caught or declared in the method signature, the program properly catches it using a try-catch block and prints an informative message. Then, the program moves on to execute the divideByZero() method, which throws an unchecked exception (ArithmeticException) at runtime due to division by zero. This too is handled in a separate try-catch block. As a result, both exceptions are caught and processed gracefully, demonstrating the proper use of exception handling to prevent program termination and maintain control over error conditions.

5. Write a Program to Handle Multiple Exceptions with Separate catch Blocks?

Algorithm :

  • Start :
    • Execution begins in the main method.
  • Enter try Block:
    • The program enters the try block and begins executing statements.
  • ArithmeticException Occurs:
    • The expression 10 / 0 is evaluated, which causes a division by zero, resulting in an ArithmeticException.
  • Control Jumps to Catch Block:
    • As soon as the ArithmeticException occurs, execution of the remaining code in the try block is skipped.
    • Control is transferred to the first matching catch block — in this case, catch (ArithmeticException e).
  • Exception Handled:
    • The message Caught ArithmeticException: java.lang.ArithmeticException: / by zero is printed.
  • End :
    • The program terminates normally after the exception is handled.
    • The code for simulating the NullPointerException is never reached.

Program :

  public class MultipleExceptionsExample {
      public static void main(String[] args) {
        try {
            // Simulate an ArithmeticException (division by zero)
            int result = 10 / 0;  // This will throw ArithmeticException
            // Simulate a NullPointerException
            String str = null;
            System.out.println(str.length());  // This will throw NullPointerException
        } catch (ArithmeticException e) {
            System.out.println(“Caught ArithmeticException: ” + e);
        } catch (NullPointerException e) {
            System.out.println(“Caught NullPointerException: ” + e);
        } catch (Exception e) {
            System.out.println(“Caught generic Exception: ” + e);
        }
    }
}

Output :

Caught ArithmeticException: java.lang.ArithmeticException: / by zero

Explanation :

       This Java program demonstrates how multiple specific exceptions can be caught using individual catch blocks. The try block contains two operations that could each cause a different type of exception. However, only the first statement — int result = 10 / 0 — is executed, which results in an ArithmeticException due to division by zero. When this exception occurs, Java skips the rest of the try block and looks for the first matching catch block. The exception is caught by the ArithmeticException catch block, and a message is printed. Importantly, the second statement (which would cause a NullPointerException) is never executed, so no further exceptions are triggered. This highlights how exception handling works sequentially: once an exception is thrown, execution stops in the try block and continues only after the appropriate exception is handled.

6. Write a Java program to show that the finally block is always executed, regardless of whether an exception occurs or not?

Algorithm :

  • Start Program Execution:
  • Enter First try Block:
    • Prints “Inside try block”.
  • Perform Division:
    • Executes 10 / 2, which equals 5 — no exception occurs.
  • Print Result:
    • Prints “Result: 5”.
  • Skip catch Block:
    • Since no exception occurred, the catch block is skipped.
  • Execute finally Block:
    • Always executes — prints “Finally block is always executed”.
  • Enter Second try Block:
    • Prints “Inside another try block”.
  • Perform Division (with Exception):
    • Executes 10 / 0, which causes an ArithmeticException.
  • Catch the Exception:
    • The catch block handles the exception and prints:
      “Caught ArithmeticException: java.lang.ArithmeticException: / by zero”.
  • Execute finally Block:
    • Regardless of the exception, the finally block executes and prints:
      “Finally block is always executed, even after exception”.
  • Program Ends:
    • Normal termination after handling both blocks.

Program :

public class FinallyBlockExample {
       public static void main(String[] args) {
        try {
            System.out.println(“Inside try block”);
            int result = 10 / 2;  // No exception here
            System.out.println(“Result: ” + result);
        } catch (ArithmeticException e) {
            System.out.println(“Caught ArithmeticException: ” + e);
        } finally {
            System.out.println(“Finally block is always executed”);
        }
        try {
            System.out.println(“Inside another try block”);
            int result = 10 / 0;  // This will throw ArithmeticException
        } catch (ArithmeticException e) {
            System.out.println(“Caught ArithmeticException: ” + e);
        } finally {
            System.out.println(“Finally block is always executed, even after exception”);
        }
    }
}

Output :

Inside try block
Result: 5
Finally block is always executed
Inside another try block
Caught ArithmeticException: java.lang.ArithmeticException: / by zero
Finally block is always executed, even after exception

Explanation :

          This program demonstrates the use of the finally block in Java, which executes whether an exception is thrown or not. In the first try block, the division 10 / 2 is performed without any exception, so the program prints the result and skips the catch block. However, the finally block still runs, confirming that it executes regardless of whether an exception occurred. In the second try block, a division by zero triggers an ArithmeticException, which is caught and handled in the catch block. Again, the finally block runs after the exception is handled.

7. Write a Java program to demonstrate how an exception is propagated from one method to another using the throws keyword. Propagate an ArithmeticException from a method and handle it in the calling method?

Algorithm :

  • Start Program Execution:
    • The program begins execution in the main method.
  • Call divideNumbers():
    • Inside the try block, the method divideNumbers() is called.
  • Exception Thrown in divideNumbers():
    • The method executes 10 / 0, which causes an ArithmeticException due to division by zero.
  • Exception Propagated to main():
    • Since divideNumbers() does not handle the exception, it is propagated back to the calling method, main().
  •  Exception Caught in main():
    • The catch block in main() catches the ArithmeticException.
  • Print Error Message:
    • The message “Caught ArithmeticException: java.lang.ArithmeticException: / by zero” is printed to the console.
  • Program Ends Gracefully:
    • The exception is handled, and the program terminates normally.

Program :

    public class ExceptionPropagationExample {
    public static void divideNumbers() throws ArithmeticException {
        int result = 10 / 0; 
    }
    public static void main(String[] args) {
        try {
            divideNumbers();  // Calling the method that throws ArithmeticException
        } catch (ArithmeticException e) {
            System.out.println(“Caught ArithmeticException: ” + e);
        }
    }
}

Output :

Caught ArithmeticException: java.lang.ArithmeticException: / by zero

Explanation :

        This program demonstrates exception propagation in Java. The method divideNumbers() performs a division by zero, which throws an ArithmeticException. Since the exception is not handled within the method, it is propagated up to the calling method, main(). In main(), the exception is caught using a try-catch block. This shows how exceptions can move up the call stack until they are either caught and handled or cause the program to crash. By catching the exception in main(), the program avoids abnormal termination and completes execution smoothly.

8. Write a Java program that creates a custom exception called AgeNotValidException. Use this exception to validate a person’s age and throw the exception if the age is less than 18?

Algorithm :

  • Program Starts:
    • Execution begins in the main method.
  • Call validateAge(16):
    • The method validateAge is called with age = 16.
  • Condition Check:
    • Inside the method, it checks if age < 18. Since 16 < 18 is true, the condition is met.
  • Throw Custom Exception:
    • A new AgeNotValidException is thrown with the message “Age is not valid. Must be 18 or older.”.
  • Catch the Exception:
    • Control moves to the catch block in main(), and the message is printed:
      “Caught exception: Age is not valid. Must be 18 or older.”.
  • Call validateAge(20):
    • The method is called again with age = 20.
  • Condition Check:
    • The condition age < 18 is false, so no exception is thrown.
  • Print Valid Message:
    • The message “Age is valid: 20” is printed.
  • Program Ends:
    • Both validations are complete, and the program ends normally.

Program :

class AgeNotValidException extends Exception {
    public AgeNotValidException(String message) {
        super(message);
    }
}
public class AgeValidation {
    public static void validateAge(int age) throws AgeNotValidException {
        if (age < 18) {
            throw new AgeNotValidException(“Age is not valid. Must be 18 or older.”);
        } else {
            System.out.println(“Age is valid: ” + age);
        }
    }
    public static void main(String[] args) {
        try {
            validateAge(16); 
        } catch (AgeNotValidException e) {
            System.out.println(“Caught exception: ” + e.getMessage());
        }
        try {
            validateAge(20); 
        } catch (AgeNotValidException e) {
            System.out.println(“Caught exception: ” + e.getMessage());
        }
    }
}

Output :

 Caught exception: Age is not valid. Must be 18 or older.
 Age is valid: 20

Explanation :

          This program demonstrates the use of a custom exception in Java to enforce age validation. A user-defined exception class AgeNotValidException extends Exception and allows a custom message to be passed when the exception is thrown. In the main method, the program first calls validateAge(16), which fails the age check and throws the custom exception. This exception is caught and handled, and the appropriate message is displayed. Next, it calls validateAge(20), which passes the validation, and the program prints a confirmation that the age is valid. This approach shows how custom exceptions can be used to enforce business logic and handle specific error cases in a clean and meaningful way.

9. Write a Java program that uses the throw keyword to throw an IllegalArgumentException when an invalid age (less than 18) is passed to the checkAge() method?

Algorithm :

  • Program Starts:
  • Call checkAge(16):
    1. The checkAge method is called with age = 16.
  • Condition Check:
    1. Inside checkAge, it checks if age < 18. Since this is true, it throws an IllegalArgumentException with the message “Invalid age: Age must be 18 or older.”.
  • Catch the Exception:
    1. Control jumps to the catch block, and it prints:
      “Caught exception: Invalid age: Age must be 18 or older.”.
  • Second Age Check (Valid Age):
  • Call checkAge(20):
    • The method is called again with age = 20.
  • Condition Check:
    • Since age < 18 is false, no exception is thrown.
  • Print Valid Age:
    • It prints “Age is valid: 20”.
  • Program Ends:
    • All statements execute successfully, and the program ends normally.

Program :

public class AgeValidation {
    public static void checkAge(int age) {
        if (age < 18) {
            throw new IllegalArgumentException(“Invalid age: Age must be 18 or older.”);
        } else {
            System.out.println(“Age is valid: ” + age);
        }
    }
    public static void main(String[] args) {
        try {
            checkAge(16);
        } catch (IllegalArgumentException e) {
            System.out.println(“Caught exception: ” + e.getMessage());
        }
        try {
            checkAge(20);  // Valid age
        } catch (IllegalArgumentException e) {
            System.out.println(“Caught exception: ” + e.getMessage());
        }
    }
}

Output :

Caught exception: Invalid age: Age must be 18 or older.
 Age is valid: 20

Explanation :

         This program demonstrates the use of built-in unchecked exceptions for input validation. The checkAge method checks whether the input age is less than 18. If it is, an IllegalArgumentException is thrown with a descriptive message. The main method handles this exception using a try-catch block. When checkAge(16) is called, it triggers the exception, and the message is printed. When checkAge(20) is called, the age passes the check, and a confirmation message is displayed. This shows how unchecked exceptions like IllegalArgumentException can be effectively used for simple validation logic in Java.

10. Write a Java program to demonstrate how a NumberFormatException occurs when trying to convert a non-numeric string into an integer. Handle the exception gracefully and display an error message?

Algorithm :

  • Program Starts:
  • Define a Non-Numeric String:
    • A string variable str is assigned the value “abc123”, which contains alphabetic characters and cannot be converted to a number.
  • Enter try Block:
    • The program enters the try block and attempts to convert the string to an integer using Integer.parseInt(str).
  • Exception Thrown:
    • Since “abc123” is not a valid numeric string, Java throws a NumberFormatException.
  • Control Jumps to catch Block:
    • The exception is caught by the catch (NumberFormatException e) block.
  • Error Message Displayed:
    • The program prints:
      “Error: Invalid input. Cannot convert ‘abc123’ to a number.”
  • Program Ends :
    • The exception is handled, and the program completes without crashing.

Program :

public class NumberFormatExceptionExample {
        public static void main(String[] args) {
        String str = “abc123”;  // Non-numeric string
        try {
            // Attempt to convert the non-numeric string to an integer
            int number = Integer.parseInt(str);
            System.out.println(“Converted number: ” + number);
        } catch (NumberFormatException e) {
            // Handle the exception gracefully and display an error message
            System.out.println(“Error: Invalid input. Cannot convert ‘” + str + “‘ to a number.”);
        }
    }
}

Output :

Error: Invalid input. Cannot convert ‘abc123’ to a number.

Explanation :

        This program illustrates how Java handles improper number conversions using the built-in NumberFormatException. The string “abc123” contains alphabetic characters, so when the program tries to convert it into an integer using Integer.parseInt, it fails and throws a NumberFormatException. The error is caught in a catch block, and a user-friendly error message is displayed instead of allowing the program to crash.

11. Write a Java program that causes an infinite recursion and throws a StackOverflowError. Catch the error and display an appropriate message?

Algorithm :

  • Start
  •  Initialization of Program:
    • The execution flow starts from the main method.
  •  Invocation within Try Block:
    • Inside the try block, the method causeStackOverflow() is invoked.
  • Recursive Execution Begins:
    • The method begins calling itself repeatedly without any condition to stop (no base case).
  • Growth of Call Stack:
    • Each recursive call adds a new frame to the call stack, leading to continuous memory usage.
  • Memory Limit Reached:
    • Since the recursion is infinite, the stack eventually fills up, exceeding its limit.
  • StackOverflowError Triggered:
    • The Java runtime detects the stack overflow and throws a StackOverflowError.
  • Exception Caught:
    • Control is passed to the catch block, where the error is caught.
  • Error Message Displayed:
    • The program prints:
      “Error: StackOverflowError occurred due to infinite recursion.”
  • Safe Program Termination:
    • The error is managed properly, allowing the program to end without crashing.
  • End

Program :

 public class StackOverflowExample {
    public static void causeStackOverflow() {
        causeStackOverflow(); 
    }
    public static void main(String[] args) {
        try {
            causeStackOverflow(); 
        } catch (StackOverflowError e) {
            // Catching the StackOverflowError and displaying the message
            System.out.println(“Error: StackOverflowError occurred due to infinite recursion.”);
        }
    }
}

Output :

Error: StackOverflowError occurred due to infinite recursion.

Explanation :

This program demonstrates how infinite recursion leads to a StackOverflowError in Java. The method causeStackOverflow() recursively calls itself without any stopping condition, which causes the JVM’s call stack to keep growing until it runs out of memory. Once the stack limit is exceeded, a StackOverflowError is thrown. The main method includes a try-catch block that catches this error and prints a user-friendly message. This illustrates the importance of using proper termination conditions in recursive methods to avoid such errors and ensure safe program execution.

12. Write a Java program that tries to allocate a large amount of memory (e.g., by creating a very large array) to intentionally trigger an OutOfMemoryError. Handle the error and display an appropriate message?

Algorithm :

  • .  Program Begins:
    • The execution starts in the main method.
  •  Enter try Block:
    • The program enters the try block and attempts to execute the code inside.
  • Memory Allocation Attempt:
    • It tries to create an integer array of size Integer.MAX_VALUE (which is 2,147,483,647 elements).
  •  Memory Exceeds Limit:
    • The required memory to allocate this array is extremely high (over 8 GB for an int array).
    • The JVM usually cannot provide that much contiguous memory, especially depending on system limitations and heap size settings.
  • OutOfMemoryError Thrown:
    • Because the JVM cannot allocate the requested memory, it throws an OutOfMemoryError.
  • Error Caught:
    • The error is caught by the catch block that handles OutOfMemoryError.
  • Error Message Displayed:
    • The message
      “Error: OutOfMemoryError occurred. The system ran out of memory.”
      is printed.
  • Program Ends :
    • Despite the critical error, the program does not crash and exits gracefully.

Program :

public class OutOfMemoryErrorExample {
    public static void main(String[] args) {
        try {
            // Trying to allocate a large array that exceeds the memory limit
            int[] largeArray = new int[Integer.MAX_VALUE];  // This will likely cause an OutOfMemoryError
        } catch (OutOfMemoryError e) {
            // Catching the OutOfMemoryError and displaying an appropriate message
            System.out.println(“Error: OutOfMemoryError occurred. The system ran out of memory.”);
        }
    }
}

Output :

Error: OutOfMemoryError occurred. The system ran out of memory.

Explanation :

      This program demonstrates what happens when the Java Virtual Machine runs out of heap memory due to excessive allocation. It tries to create an array with over two billion elements, which demands more memory than the system can provide. As a result, the JVM throws an OutOfMemoryError. This error is a subclass of VirtualMachineError, indicating a serious resource issue. However, the program handles the error using a try-catch block, allowing it to report the issue cleanly and exit without crashing.

13. Write a Java program to demonstrate handling exceptions with multiple nested try-catch blocks. Ensure that exceptions are caught at both the inner and outer levels of the try-catch hierarchy?

Algorithm :

  • Start :
  • Enter Outer try Block:
    • The outer try block starts and prints:
      “Outer try block starts.”
  • Enter Inner try Block:
    • The inner try block starts and prints:
      “Inner try block starts.”
  • ArithmeticException Occurs:
    • Code attempts int result = 10 / 0;
      This throws an ArithmeticException.
  • Control Transfers to Inner catch:
    • The inner catch block catches the exception and prints:
      “Caught ArithmeticException in inner block: java.lang.ArithmeticException: / by zero”
  • Continue in Outer try Block:
    • Control moves past the inner block and executes String str = null;
  • NullPointerException Occurs:
    • It tries to access str.length(), which throws a NullPointerException.
  • Control Transfers to Outer catch:
    • The outer catch block for NullPointerException handles the error and prints:
      “Caught NullPointerException in outer block: java.lang.NullPointerException”
  • Program Ends :
    • After exception handling, the program prints:
      “Program continues after exception handling.”

Program :

      public class NestedTryCatchExample {
      public static void main(String[] args) {
        try {
            System.out.println(“Outer try block starts.”);
            try {
                System.out.println(“Inner try block starts.”);
                int result = 10 / 0; 
                System.out.println(“Result: ” + result);  // This will not be executed
            } catch (ArithmeticException e) {
                System.out.println(“Caught ArithmeticException in inner block: ” + e);
            }
            String str = null;
            System.out.println(str.length());  // This will throw NullPointerException
        } catch (NullPointerException e) {
            System.out.println(“Caught NullPointerException in outer block: ” + e);
        } catch (Exception e) {
            System.out.println(“Caught general Exception in outer block: ” + e);
        }
        System.out.println(“Program continues after exception handling.”);
    }
}

Output :

Outer try block starts.
Inner try block starts.
Caught ArithmeticException in inner block: java.lang.ArithmeticException: / by zero
Caught NullPointerException in outer block: java.lang.NullPointerException
Program continues after exception handling.

Explanation :

        This program demonstrates the use of nested try-catch blocks for handling multiple exceptions at different levels. The outer try block starts and enters an inner try block where an ArithmeticException occurs due to division by zero. This is caught by the inner catch, ensuring the outer block can continue executing. After exiting the inner block, the outer try block proceeds with a statement that throws a NullPointerException. This exception is caught by the outer catch block. Finally, the program prints a message indicating it continues after all exceptions are properly handled. This structure allows fine-grained control over exception handling.

14. Write a Java program that attempts to access an invalid index of an array, triggering an ArrayIndexOutOfBoundsException. Handle the exception and print a relevant message?

Algorithm :

  • Start:
  • Array Declaration:
    1. An integer array numbers is initialized with 5 elements: {1, 2, 3, 4, 5}.
  • Enter try Block:
    1. The program enters the try block to attempt accessing an array element.
  • Invalid Index Access:
    1. It tries to access numbers[10], but valid indices are only from 0 to 4.
  • Exception Thrown:
    1. Since index 10 is out of bounds, Java throws an ArrayIndexOutOfBoundsException.
  • Catch Block Executes:
    1. The catch block catches the exception and prints:
      “Error: ArrayIndexOutOfBoundsException occurred. Invalid index access.”
  • Ends :
    • The program ends without crashing due to proper exception handling.

Program :

  public class ArrayIndexOutOfBoundsExample {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};  // Array with 5 elements
        try {
            System.out.println(“Accessing element at index 10: ” + numbers[10]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println(“Error: ArrayIndexOutOfBoundsException occurred. Invalid index access.”);
        }
    }
}

Output :

Error: ArrayIndexOutOfBoundsException occurred. Invalid index access.

Explanation :

      This program demonstrates how Java handles attempts to access elements outside the valid range of an array. It defines an array with 5 elements and then tries to access the element at index 10, which doesn’t exist. This results in an ArrayIndexOutOfBoundsException. The exception is caught using a try-catch block, and an appropriate error message is displayed. By handling the exception, the program avoids crashing and ends gracefully, showing the importance of checking index boundaries during array operations.

15. Write a Java program that reads data from a file. If the file does not exist, handle the FileNotFoundException and display a message?

Algorithm :

  • Program Starts:
    • The main method is executed.
  • File Declaration:
    • A File object is created for “example.txt”.
  • Enter try Block:
    • The program tries to open and read the file using a Scanner.
  • File Not Found Check:
    • If the file “example.txt” does not exist in the working directory, a FileNotFoundException is thrown.
  • Catch Block Executes:
    • The exception is caught, and an error message is printed:
      “Error: FileNotFoundException. The file does not exist.”
  • If File Exists (Optional Path):
    • If the file does exist, the program reads each line and prints it.
  • Scanner Closes:
    • After reading, the scanner is closed to free resources.
  • Program Ends Gracefully:
    • Whether the file is found or not, the program completes without crashing due to proper exception handling.

Program :

 import java.io.File;
 import java.io.FileNotFoundException;
 import java.util.Scanner;
  public class FileNotFoundExceptionExample {
    public static void main(String[] args) {
        File file = new File(“example.txt”);
        try {
            Scanner scanner = new Scanner(file);
            System.out.println(“Reading from the file…”);
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line); 
            }
            scanner.close(); 
        } catch (FileNotFoundException e) {
            System.out.println(“Error: FileNotFoundException. The file does not exist.”);
        }
    }
}

Output :

Error: FileNotFoundException. The file does not exist.

Explanation :

     This program attempts to read from a file named “example.txt” using a Scanner. If the file is not found, a FileNotFoundException is thrown and caught, displaying an error message. If the file exists, its contents are printed line by line. This demonstrates how to handle checked exceptions in file operations and ensures smooth program execution even when files are missing.

16. Write a Java program to demonstrate a ClassCastException by attempting to cast an object to an incompatible type. Handle the exception and print the error message?

Algorithm :

  • Program Starts:
  • Object Declaration:
    • An Object named obj is created and assigned an Integer value (100).
  • Enter try Block:
    • The program enters the try block and attempts to cast the obj (which is of type Object) to a String.
  • Invalid Type Casting:
    • Since obj actually holds an Integer value, the attempt to cast it to a String results in a ClassCastException.
  • ClassCastException Thrown:
    • The JVM throws a ClassCastException because the cast from Integer to String is not valid.
  • Catch Block Executes:
    • The catch block catches the exception and prints:
      “Error: ClassCastException occurred. Incompatible type casting.”
  • Exception Details Displayed:
    • The program prints additional details of the exception using e.getMessage(), which indicates that the cast is invalid.
  • Program Ends Gracefully:
    • Despite the error, the program exits gracefully without crashing, thanks to the proper exception handling.

Program :

        public class ClassCastExceptionExample {
       public static void main(String[] args) {
        Object obj = new Integer(100);
        try {
            String str = (String) obj;
            System.out.println(“Cast successful: ” + str);
        } catch (ClassCastException e) {
            System.out.println(“Error: ClassCastException occurred. Incompatible type casting.”);
            System.out.println(“Details: ” + e.getMessage());
        }
    }
}

Output :

 Error: ClassCastException occurred. Incompatible type casting.
 Details: java.lang.Integer cannot be cast to java.lang.String

Explanation :

        In this program, an attempt is made to cast an Integer object (obj) to a String. However, since Integer and String are completely different types, this type of casting is not allowed and leads to a ClassCastException. The exception is thrown at runtime, and the catch block handles it by printing an error message: “Error: ClassCastException occurred. Incompatible type casting.”. The message from the exception is also printed to provide more details. By using a try-catch block, the program handles the error gracefully, ensuring that the program doesn’t crash unexpectedly.

17. Write a Java program that reads content from a file using FileReader and handles the IOException that might occur during the file reading process?

Algorithm :

  • Program Starts:
  • File Path Declaration:
    • A String variable filePath is declared with the value “example.txt”, which is the file to be read.
  • Enter try-with-resources Block:
    • The try-with-resources block attempts to open the file using FileReader, automatically managing resource closure.
  • Read Characters from File:
    • The program enters a while loop where it reads the file character by character using fileReader.read().
    • Each character is printed to the console as it is read, using System.out.print((char) character).
  • End of File Reached:
    • Once the end of the file is reached, fileReader.read() returns -1, causing the while loop to terminate.
  • Exit Try Block:
    • The try-with-resources block ensures that the fileReader is automatically closed after reading.
  • IOException Handling:
    • If an error occurs during file reading (such as the file not being found or permission issues), an IOException is thrown.
    • The catch block catches the IOException and prints the error message:
    • “Error: IOException occurred while reading the file.”
    • The details of the exception are printed using e.getMessage().
  • Program Ends :
    • If no error occurs, the program ends after reading the file. If an error occurs, the program exits after handling the exception.

Program :

    import java.io.FileReader;
    import java.io.IOException;
   public class FileReaderIOExceptionExample {
    public static void main(String[] args) {
        String filePath = “example.txt”; 
        try (FileReader fileReader = new FileReader(filePath)) {
            int character;
            System.out.println(“Reading content from file:”);
            while ((character = fileReader.read()) != -1) {
                System.out.print((char) character);  // Print each character from the file
            }
        } catch (IOException e) {
            System.out.println(“Error: IOException occurred while reading the file.”);
            System.out.println(“Details: ” + e.getMessage());
        }
    }
}

Output :

 Error: IOException occurred while reading the file.
 Details: example.txt (The system cannot find the file specified)

Explanation :

This program demonstrates reading a file character by character using FileReader in Java. It uses a try-with-resources block to open the file and ensures that the FileReader is closed automatically after reading. If the file is read successfully, its content is printed character by character. If an IOException occurs (e.g., file not found), it is caught by the catch block, and an error message with the exception details is displayed. This showcases proper handling of file I/O and exception management in Java, ensuring smooth program execution even when errors occur.

18. Write a Java program that demonstrates how to handle a NullPointerException. The program should attempt to call a method on a null object and handle the exception gracefully?

Algorithm :

  • Starts:
    • The main method is executed.
  • Variable Declaration:
    • A String variable str is declared and initialized to null.
  • Enter try Block:
    • The program enters the try block and attempts to call the length() method on the str variable.
  • NullPointerException Thrown:
    • Since str is null, attempting to call str.length() results in a NullPointerException.
  • Exception Caught:
    • The catch block catches the NullPointerException and prints:
      “Error: NullPointerException occurred. Cannot call method on a null object.”
  • Program Continues:
    • After handling the exception, the program continues and prints:
      “Program continues after exception handling.”
  • Ends :
  • Despite the exception, the program doesn’t crash due to proper exception handling and finishes execution.

Program :

public class NullPointerExceptionExample {
    public static void main(String[] args) {
        String str = null; 
        try {
            int length = str.length(); 
            System.out.println(“Length of the string: ” + length);
        } catch (NullPointerException e) {
            System.out.println(“Error: NullPointerException occurred. Cannot call method on a null object.”);
        } 
        System.out.println(“Program continues after exception handling.”);
    }
}

Output :

Error: NullPointerException occurred. Cannot call method on a null object.
  Program continues after exception handling.

Explanation :

      In this program, the variable str is initialized to null. The program attempts to call the length() method on str in the try block. However, since str is null, calling any method on a null object results in a NullPointerException. This is a runtime exception in Java that occurs when trying to invoke a method or access a field on a null object reference. The exception is caught by the catch block, which then prints an error message: “Error: NullPointerException occurred. Cannot call method on a null object.”. After handling the exception, the program continues and prints: “Program continues after exception handling.”.

Leave a Reply

Your email address will not be published. Required fields are marked *