Java Assignment- 5
Exception Handling
Basic Questions
- In simple words, explain what an exception is in Java and why exceptions occur during program execution.
- In one or two lines each, explain the difference between checked and unchecked exceptions with one example name for each type.
- Draw or write (as comments) a small tree to show the Java exception hierarchy starting from Throwable → Exception and Error, and then a few common subclasses.
- Write a small program that divides two integers and uses try–catch to handle any ArithmeticException (divide by zero). Print a friendly message.
- Write a program that reads an integer from a string using Integer.parseInt(). Use try–catch to handle NumberFormatException and print the error message.
- Write a program that accesses arr[5] in an array of length 3. Use try–catch to handle ArrayIndexOutOfBoundsException and print a clear message.
- Write a program that uses a String reference set to null and tries to call .length(). Catch NullPointerException and print a simple explanation.
- Write a program that uses multiple catch blocks to handle NumberFormatException and NullPointerException separately. Print a different message for each case.
- Write a program that demonstrates the finally block by printing a message from finally regardless of whether an exception occurs or not.
- Write a method that throws a new IllegalArgumentException using the throw keyword when the input is negative. Call it and handle the exception in main.
- Write a method with a throws declaration for IOException. In main, call this method inside a try–catch and print a message when the exception is caught.
- Create a simple custom checked exception class InvalidAgeException (extends Exception) with a constructor that accepts a message. Do not write the usage yet.
- Create a simple custom unchecked exception class BadStateException (extends RuntimeException) with a constructor that accepts a message. Do not write the usage yet.
- Write a program that tries to load a class using Class.forName(“com.abc.MissingClass”). Catch ClassNotFoundException and print a message.
- Write a program that tries to open a file path that does not exist using FileInputStream. Catch FileNotFoundException and print a message.
- Write a program that reads text from an existing file using try-with-resources and BufferedReader. Handle IOException and print the file content line by line.
- Write a small method simulateSql() that always throws a new SQLException. Call it from main, catch SQLException, and print a short explanation.
- Write a program that uses a multi-catch (catch (IOException | SQLException e)) and prints the exception class name received.
- Write a program that catches an exception, prints e.getMessage(), and then continues execution by printing “End of program”.
- Write a program that demonstrates a safe parse method: it returns -1 if Integer.parseInt() fails, without crashing the program.
Intermediate Questions
- Write a program that reads two integers from the command line and prints their quotient. Use two specific catch blocks: one for ArithmeticException and one for NumberFormatException. Add a finally block that prints “Done”.
- Write a method readFirstLine(String path) that uses try-with-resources to open a text file and return the first line or null if not found. Handle IOException properly.
- Create and use the custom checked exception InvalidAgeException to validate an age for registration. If age < 18, throw the exception with a clear message; catch it in main and print the message.
- Create and use the custom unchecked exception BadStateException inside a method when the system is not initialized. Catch it in main and print the message.
- Write a program that demonstrates exception propagation: methods a() calls b(), b() calls c(), and c() throws IOException. Add throws IOException in b() and c(), then catch it only in a().
- Write a method that validates a non-empty string argument. If the string is empty, throw a new IllegalArgumentException(“Empty input”). Catch it in main and print the message.
- Write a program that shows order of multiple catch blocks by catching FileNotFoundException before IOException. Explain in a comment why the order matters.
- Write a program that parses a list of integers from strings (some invalid). Use multi-catch to handle NumberFormatException and NullPointerException. Count how many failures occurred.
- Write a program that opens a file and also does a second operation that can throw SQLException. Use two separate try blocks with clear messages for each exception type.
- Write a method copyFile(String src, String dest) using try-with-resources with Files.newBufferedReader and Files.newBufferedWriter. Handle IOException and return true on success, false otherwise.
- Write a program that catches an exception, logs the message with a prefix “ERROR: ”, and then rethrows the same exception to the caller.
- Write a method that calls another method which can throw ClassNotFoundException. Use throws in your method signature and handle the exception in main.
- Write a small utility safeDivide(int a, int b) that returns OptionalInt. If b == 0, return an empty OptionalInt instead of throwing an exception. Demonstrate its use.
- Write a program that reads integers until the user types “stop”. Handle NumberFormatException for bad inputs and continue reading. When finished, print the sum.
- Write a program that uses nested try–catch: inner block may throw ArrayIndexOutOfBoundsException, outer block catches any other RuntimeException. Print which block handled the error.
- Write a method that validates a product code like “PRD-123”. If format is wrong, throw an IllegalArgumentException with a custom message describing the expected format.
- Write a program that wraps a checked exception into an unchecked one: catch IOException and throw a new RuntimeException with the original exception as the cause. Print the stack trace in main.
- Write a program that demonstrates finally used for cleanup by closing a Scanner (if not using try-with-resources). Show that finally runs even if an exception occurs.
- Write a program that collects and prints the full stack trace of an exception to a String (use StringWriter/PrintWriter), then prints it to the console.
- Write a program that reads a configuration value from a file. If the key is missing, throw a custom checked exception ConfigMissingException with a clear message. Handle it in main.
Advanced Questions
- Create a custom exception hierarchy for payments: PaymentException (checked) as base, with CardDeclinedException and InsufficientBalanceException as subclasses. Write a method pay(…) that throws the appropriate subclass based on input, and handle them separately in main.
- Write a program that demonstrates exception propagation with resources: loadData() opens a file using try-with-resources, calls parse() which may throw NumberFormatException, and validate() which may throw a custom checked exception. Catch in main and print which method failed.
- Write a program that uses a multi-catch to handle (IOException | SQLException) when processing a list of operations. For each operation, print “OK” or the exception class name.
- Write a program that rethrows a transformed exception: catch FileNotFoundException and rethrow it as a custom checked exception InputFileMissingException with a detailed message, preserving the cause.
- Create a class CloseTracker that implements AutoCloseable and prints messages on open and close. Use it in a try-with-resources block that also does an operation that may throw IOException. Show the order of messages when an exception occurs.
- Write a method readOrDefault(String path, String def) that attempts to read all text from a file. If any IOException occurs, catch it, log the message, and return the default string without rethrowing.
- Write a small program that loads a class name from user input and calls Class.forName(name). Handle ClassNotFoundException with a custom message that suggests correct usage. Continue program flow normally.
- Write a method parsePrice(String s) that returns a double. If the string is null, throw NullPointerException with a custom message; if it is not a valid number, throw NumberFormatException with a clear message; otherwise, return the parsed value. Handle both in main.
- Write a program that demonstrates wrapping and unwrapping causes: create and throw a SQLException with a cause IOException. Catch the SQLException and print both the main message and the cause’s message.
- Write a program that performs multiple steps: read config file (may throw IOException), load driver class (may throw ClassNotFoundException), and parse a numeric setting (may throw NumberFormatException). Use structured error handling to catch each type separately and print a short recovery suggestion for each.