Thursday, February 27, 2014

java exception interview questions and answers

What is Exception in Java ?
An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.

What happens when a method throws an exception ?
After a method throws an exception, the runtime system attempts to find an exception handler to handle it. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. When an appropriate handler is found, the runtime system passes the exception to the handler. If the runtime system is unable to find an appropriate exception handler,the runtime system terminates.

For example : Suppose the main method calls a method named A . A calls B and B calls a method C . C method throws exception . The problem can be described with the below diagram .



We can understand this in the steps given below :
  1. Exception occurs at method C() . The method creates an exception object and gives it to the runtime system. 
  2. The runtime system starts looking for a matching exception handler . The search starts from method C() but because it does not provide any exception handler , the call propogates down the call stack. 
  3. The runtime system looks for a handler in method B() . B also does not provide any handler so the call propagates down the call stack. 
  4. A() provides a try/catch block that catches the type of exception that was thrown by C() so runtime system passes the exception to this handler.
Explain Java Exception Hierarchy ?
The top level class in exception hierarchy is Throwable. Error and Exception extends from Throwable. Errors are the conditions that can't be recovered from so they are not handled by a java program. Exception is further extended by RuntimeException.

java exception hierarchy


What are important methods of Java Exception Class?
Below are some important methods of Exception class :

public String getMessage() 
Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor.

public Throwable getCause() Returns the cause of the exception as represented by a Throwable object. 

public String toString() Returns the name of the class concatenated with the result of getMessage()

public void printStackTrace() Prints the result of toString() along with the stack trace to System.err, the error output stream.

public StackTraceElement[] getStackTrace() Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack.

public Throwable fillInStackTrace() Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace.

What is OutOfMemoryError in Java?
OutOfMemoryError is when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector. OutOfMemoryError in Java is a subclass of VirtualMachineError.

What is the concept of multi-catch block ?
In multi-catch block , we can catch multiple exceptions in a single catch block.

Benefits : This feature can reduce code duplication and lessen the temptation to catch an overly broad exception.

Example : 
Without multi catch
catch (IOException ex){
       logger.log(ex);
       throw ex;
}
catch (SQLException ex){
       logger.log(ex);
       throw ex;
}

With multi catch
catch(SQLException | SQLException ex)
{
       logger.log(ex);
       throw ex;
}

What is difference between Checked and Unchecked Exception in Java?


Checked exeptions unchecked exceptions
Checked Exceptions follows handle or declare rule. so a method throwing a checked exception should either handle it using try-catch block or decalare it in method signature using throws keyword.Unchecked Exceptions are not required to be handled in the program or to mention them in throws clause.
Exception is the super class of all checked exceptions.RuntimeException is the super class of all unchecked exceptions.
Checked exceptions are error scenarios that are not caused by program, for example FileNotFoundException in reading a file that is not present.Unchecked exceptions are mostly programming bugs , for example NullPointerException when invoking a method on an object reference without making sure that it’s not null.


What is difference between throw and throws keyword in Java?
throws is as much a part of the method signature . Clients know if they call that method, they need to handle that exception by simply throwing it or by catching it and handling it . throws is addressed at compile time. 

public void getUserDetails() throws SQLException{
       // code
 }

throw is the actual act of letting the runtime know that something bad has happened and allows to through the exception manually.

 public public void getUserDetails() {
     if(!user.exists()) {
           throw UserNotFoundException("User does not exists in database");
     }
 }

What happens when exception is thrown by main method?
When exception is thrown by main , Java runtime system terminates.

Can we have the try block without catch or finally block?
NO . try block must have a catch or finally associated with it.

What is difference between ClassNotFoundException and NoClassDefFoundError?
ClassNotFoundException is thrown when an application tries to load in a class through its string name using:
  • The forName method in class Class. 
  • The findSystemClass method in class ClassLoader . 
  • The loadClass method in class ClassLoader.
but no definition for the class with the specified name could be found.

NoClassDefFoundError is thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.

What is StackOverflowError?
StackOverflowError error is thrown by JVM when it encounters that there is no memory left in the stack to store variables . Parameters and local variables are allocated on the stack . The common cause for a stack overflow is a bad recursive call. Typically this is caused when your recursive functions doesn't have the correct termination condition, so it ends up calling itself for ever.

What does 'Ducking' the exception mean?
If a method does not handle the exception but simply declares it using throws , the method is said to be ducking the exception.


3 comments :

  1. very nice. for java examples, visit http://java2novice.com site

    ReplyDelete
  2. Thanks...If anybody wants to know the exception handling interview questions with answers then please go through this blog http://adnjavainterview.blogspot.in/2014/06/exception-handling-questions.html

    ReplyDelete
  3. Very nice. For more examples visit http://answersz.com

    ReplyDelete