1. Write a program to what happens if an exception is not caught in Java?
public class ExceptionExample { public static void main(String[] args) { method1(); } static void method1() { method2(); } static void method2() { int result = 10 / 0; } } |
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) |
2. Write a program to what is the difference between throws and throw in Java?
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 |
3. How do you handle multiple exceptions in a single catch block?
public class MultipleExceptionsExample { public static void main(String[] args) { try { int result = 10 / 0; String str = null; str.length(); } catch (ArithmeticException | NullPointerException e) { System.out.println(“Caught exception: ” + e); } } } |
Output :
Caught exception: java.lang.ArithmeticException: / by zero |
4. Write a program for checked exception and unchecked exception?
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 |
5. Write a program to handle multiple exceptions with separate catch blocks?
public class MultipleExceptionsExample { public static void main(String[] args) { try { int result = 10 / 0; String str = null; System.out.println(str.length()); } 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 |
6. Write a Java program to show that the finally block is always executed, regardless of whether an exception occurs or not?
public class FinallyBlockExample { public static void main(String[] args) { try { System.out.println(“Inside try block”); int result = 10 / 2; 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; } 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 |
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?
public class ExceptionPropagationExample { public static void divideNumbers() throws ArithmeticException { int result = 10 / 0; } public static void main(String[] args) { try { divideNumbers(); } catch (ArithmeticException e) { System.out.println(“Caught ArithmeticException: ” + e); } } } |
Output :
Caught ArithmeticException: java.lang.ArithmeticException: / by zero |
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?
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 |
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?
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); } 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 |
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?
public class NumberFormatExceptionExample { public static void main(String[] args) { String str = “abc123”; try { int number = Integer.parseInt(str); System.out.println(“Converted number: ” + number); } catch (NumberFormatException e) { System.out.println(“Error: Invalid input. Cannot convert ‘” + str + “‘ to a number.”); } } } |
Output :
Error: Invalid input. Cannot convert ‘abc123’ to a number. |
11. Write a Java program that causes an infinite recursion and throws a StackOverflowError catch the error and display an appropriate message?
public class StackOverflowExample { public static void causeStackOverflow() { causeStackOverflow(); } public static void main(String[] args) { try { causeStackOverflow(); } catch (StackOverflowError e) { System.out.println(“Error: StackOverflowError occurred due to infinite recursion.”); } } } |
Output :
Error: StackOverflowError occurred due to infinite recursion. |
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?
public class OutOfMemoryErrorExample { public static void main(String[] args) { try { int[] largeArray = new int[Integer.MAX_VALUE]; } catch (OutOfMemoryError e) { System.out.println(“Error: OutOfMemoryError occurred. The system ran out of memory.”); } } } |
Output :
Error: OutOfMemoryError occurred. The system ran out of memory. |
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?
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); } catch (ArithmeticException e) { System.out.println(“Caught ArithmeticException in inner block: ” + e); } String str = null; System.out.println(str.length()); } 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. |
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?
public class ArrayIndexOutOfBoundsExample { public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5}; 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. |
15. Write a Java program that reads data from a file. If the file does not exist, handle the FileNotFoundException and display a message?
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. |
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?
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 |
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?
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); } } 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) |
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?
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. |