Java Exception handling Question and Answers

  1. What is an Exception in Java?
    • Exceptions are events that disrupt the normal flow of a program’s instructions. In Java, exceptions are objects that wrap an error event that occurred within a method and indicates that the method was unable to complete its task.
  2. Can you explain the difference between checked and unchecked exceptions?
    • Checked exceptions are checked at compile-time, and the programmer is required to handle these exceptions, either with a try-catch block or by declaring them with a throws keyword in the method signature. Unchecked exceptions are not checked at compile-time, and they include runtime exceptions and errors. They are usually due to programming errors and faulty logic.
  3. How does the try-catch-finally block work in Java?
    • The try block encloses code that might throw an exception, the catch block catches and handles the exception, and the finally block executes after the try-catch blocks regardless of whether an exception was thrown or caught, typically used for cleanup activities.
  4. What is the purpose of the finally block in Java? Does the finally block always execute?
    • The finally block is used to execute necessary cleanup code such as closing resources. It always executes except in scenarios where the JVM exits during the try or catch block execution, or if the thread executing the try-catch block gets killed.
  5. How can you create a custom exception in Java?
    • Custom exceptions are created by extending the Exception class (for checked exceptions) or the RuntimeException class (for unchecked exceptions). The class can have constructors to initialize the exception object with a message or cause.
  6. What is the difference between the throw and throws keyword in Java?
    • The throw keyword is used within a method to throw an exception, while the throws keyword is part of the method signature and declares that a method might throw exceptions, requiring the caller to handle or declare them.
  7. Can you catch multiple exceptions in a single catch block? How?
    • Yes, since Java 7, you can catch multiple exceptions in a single catch block using the pipe character (|) to separate the exception types. This feature reduces code duplication.
  8. Explain exception propagation in Java.
    • Exception propagation allows an exception to be thrown from the method where it occurred and caught in another method. If a method does not handle an exception, it propagates to the caller method, and this process continues up the call stack.
  9. What is the difference between Error and Exception in Java?
    • Error is used for critical system errors that applications should not try to handle. Exception represents conditions that applications might want to catch and handle.
  10. How does Java handle uncaught exceptions?
    • Uncaught exceptions are handled by the JVM’s default uncaught exception handler, which typically prints the exception’s stack trace to System.err.
  11. What are the best practices for exception handling in Java?
    • Best practices include not catching generic exceptions, not ignoring exceptions, cleaning up resources in a finally block or using try-with-resources, and providing informative error messages.
  12. What is the try-with-resources statement in Java?
    • Introduced in Java 7, it automatically manages resource closure without a finally block for resources that implement the AutoCloseable or Closeable interface.
  13. Can a try block exist without a catch block?
    • Yes, a try block can exist without a catch block if it is followed by a finally block. However, it’s more common to see try with either catch, finally, or both.
  14. What is the use of the throw keyword? Give an example.
    • The throw keyword is used to explicitly throw an exception. Example: if(x < 0) throw new IllegalArgumentException("x must be non-negative");.
  15. What is a stack trace, and how can it be useful in exception handling?
    • A stack trace is a report of the active stack frames at a certain point in time during the execution of a program. It is useful for debugging because it shows the call path that led to the exception.
  16. What is a chained exception in Java?
    • Chained exception is a mechanism to associate another exception with an exception. This is done using the initCause method or by providing the cause through a constructor that takes a Throwable.
  17. Can you override a method that throws an exception with a method that doesn’t throw any exception?
    • Yes, an overriding method in Java can completely remove the throws clause, as the subclass method can declare fewer exceptions than the superclass method.
  18. What is the difference between final, finally, and finalize in Java?
    • final is a keyword to define constants or immutable objects, or to prevent inheritance and overriding. finally is a block that follows a try-catch structure, ensuring code execution regardless of exceptions. finalize is a method that the garbage collector calls before object destruction, providing a chance to free resources.
  19. How can you handle an exception thrown by a constructor?
    • Exceptions thrown by constructors can be handled using a try-catch block around the object creation statement. This allows the program to take corrective action or fail gracefully.
  20. Is it possible to execute some code even before JVM shuts down due to an unhandled exception? If yes, how?
    • Yes, using Runtime.getRuntime().addShutdownHook(Thread hook), one can add a shutdown hook that executes before the JVM shuts down, allowing for cleanup or logging actions.
  21. What is the significance of the throws clause in a method signature?
    • The throws clause in a method signature indicates that the method may throw the specified exceptions, informing method callers so they can handle or propagate these exceptions.
  22. How do you handle checked exceptions in lambda expressions in Java?
    • Since lambda expressions cannot directly handle checked exceptions, a common workaround is to wrap lambda body code in a try-catch block or use a wrapper method that handles the exception.
  23. What are the consequences of swallowing exceptions?
    • Swallowing exceptions can hide underlying problems, making debugging difficult, and may lead to the application continuing in an unknown state, potentially causing more errors.
  24. How does exception handling work with method overloading?
    • Exception handling is independent of method overloading. Overloaded methods can throw different exceptions, but the calling code must handle the exceptions based on the method signature it calls.
  25. What is a rethrown exception, and how is it used?
    • A rethrown exception is caught and then thrown again using the throw keyword. It’s used to allow further handling up the call stack while possibly performing some operations before rethrowing, such as logging.
  26. How do you ensure that a resource is freed or closed after an exception occurs?
    • The try-with-resources statement or a finally block ensures resources are closed or freed even if an exception occurs, by explicitly closing resources in finally or declaring resources in the try-with-resources statement.
  27. What is an exception hierarchy in Java?
    • Java’s exception hierarchy stems from the Throwable class, with two main subclasses: Error (used for system errors) and Exception (used for conditions that user code should catch), including RuntimeException for unchecked exceptions.
  28. Can you throw an exception from a static initializer block? If so, what happens?
    • Yes, an exception can be thrown from a static initializer block. If it’s unchecked, it will propagate normally. If it’s checked, it must be caught within the static block. Failure to do so will result in a runtime error when the class is accessed.
  29. What are suppressed exceptions, and how are they handled in Java?
    • Suppressed exceptions occur in the context of try-with-resources, where an exception thrown from the try-block can be suppressed by an exception thrown when closing the resource. They can be retrieved using the getSuppressed method.
  30. How can logging help in exception handling?
    • Logging provides a way to record exception information, which can be invaluable for debugging. It can capture the exception message, stack trace, and the state of the system at the time of the exception, helping in diagnosing and fixing the issue.