Java Interview Questions - Exceptions

06 Nov 2011 | By Mihai Roman | Tags java exceptions
  1. What are Checked and UnChecked Exception?
    Checked: subclass of Exception except RuntimeException. Unchecked: Error, RuntimeException and their subclasses. For unchecked exceptions, the compiler does not force the programmer to either catch the exception or declare it in the throws clause.
  2. What is the difference between and error and an exception?
    Errors should be irrecoverable. However there’s nothing stopping you from catching any subclass of Throwable.
  3. How to create custom exceptions?
    Extend Throwable or any of its subclasses, like Error, RuntimeException or Exception.
  4. If I want an object of my class to be thrown as an exception object, what should I do?
    Either make your class extend Throwable or any of its subclasses or delegate throwing your object to a wrapper subclass of Throwable.
  5. If my class already extends from some other class what should I do if I want an instance of my class to be thrown as an exception object?
    Java doesn’t allow extending multiple classes (unlike C++). You should delegate throwing it to a wrapper class that extends Throwable.
  6. How does an exception permeate through the code?
    An unhandled exceptions moves up the call stack until it finds a matching catch block that will be executed. If the exception is not caught anywhere, the program exist with that error.
  7. What are the different ways to handle exceptions?
    try-catch blocks or declaration in throws clause.
  8. What is the basic difference between the 2 approaches to exception handling: 1) try catch finally block and 2) specifying the candidate exceptions in the throws clause? When should you use which approach?
    1) The method is responsible of dealing with it’s own exceptions. 2) Otherwise. Making the decision is subject to patterns and anti-patterns in exception handling, not a short and decisive answer.
  9. Is it necessary that each try block must be followed by a catch block?
    No. However, in this case, it must be followed by a finally block.
  10. If I write return at the end of the try block, will the finally block still execute?
    Yes. It can also change the return value.
  11. If I write System.exit (0); at the end of the try block, will the finally block still execute?
    No.
  12. How does a try statement determine which catch clause should be used to handle an exception?
    The first matching catch block, in order of declaration.
  13. Does it matter in what order catch statements for FileNotFoundException and IOException are written?
    Yes, because the FileNotFoundException is a subclass of IOException.
  14. What is the purpose of the finally clause of a try-catch-finally statement?
    Execute code no matter if an exception is thrown or caught. Order of execution: try-catch-finally or try-finally-throw forward.

blog comments powered by Disqus