Wednesday, November 2, 2011

Exception Handling Interview Question Answer



1)    What is exception ?
An event during program execution that prevents the program from continuing normally. Generally, an error. The Java programming languages supports exceptions with the try, catch, and throw keywords. See also exception handler.

2)    What is exception handler?
A block of code that reacts to a specific type of exception. If the exception is for an error that the program can recover from, the program can resume executing after the exception handler has executed.

3)    What is throw?
A Java keyword that allows the user to throw an exception or any class that implements the "throwable" interface.

4)    What is throws?
A Java keyword used in method declarations that specify which exceptions are not handled within the method but rather passed to the next higher level of the program.

5)    What is try?
A Java keyword that defines a block of statements that may throw a Java language exception. If an exception is thrown, an optional catch block can handle specific exceptions thrown within the try block. Also, an optional finally block will be executed regardless of whether an exception is thrown or not.

6)    Which package contains exception handling related classes?
java.lang

7)    What are the two types of Exceptions?
Checked Exceptions and Unchecked Exceptions.

8)    What is the base class of all exceptions?
java.lang.Throwable

9)    What is the difference between Exception and Error in java?
·         Exception and Error are the subclasses of the Throwable class. Exception class is used for exceptional conditions that user program should catch. Error defines exceptions that are not excepted to be caught by the user program. Example is Stack Overflow.
·         The exception class defines mild error conditions that your program encounters. Exceptions can occur when trying to open the file, which does not exist, the network connection is disrupted, operands being manipulated are out of prescribed ranges, the class file you are interested in loading is missing. The error class defines serious error conditions that you should not attempt to recover from. In most cases it is advisable to let the program terminate when such an error is encountered.
·         An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.).
·         The exception class defines mild error conditions that your program encounters. Exceptions can occur when trying to open the file, which does not exist, the network connection is disrupted, operands being manipulated are out of prescribed ranges, the class file you are interested in loading is missing. The error class defines serious error conditions that you should not attempt to recover from. In most cases it is advisable to let the program terminate when such an error is encountered.

10) What is the difference between throw and throws?
  • Throw is used to explicitly raise an exception within the program, the statement would be throw new Exception ();
  • Throws clause is used to indicate the exceptions that are not handled by the method. It must specify this behavior so the callers of the method can guard against the exceptions. Throws is specified in the method signature. If multiple exceptions are not handled, then they are separated by a comma. The statement would be as follows: public void doSomething() throws IOException,MyException{}

  • The throw keyword denotes a statement that causes an exception to be initiated. It takes the Exception object to be thrown as argument. The exception will be caught by an immediately encompassing try-catch construction or propagated further up the calling hierarchy.
  • The throws keyword is a modifier of a method that designates that exceptions may come out of the method, either by virtue of the method throwing the exception itself or because it fails to catch such exceptions that a method it calls may throw.

11) Differentiate between Checked Exceptions and Unchecked Exceptions?
Checked Exception is Compile time.
Unchecked Exception is Run time.
·         Checked Exceptions are those exceptions which should be explicitly handled by the calling method. Unhandled checked exceptions results in compilation error.
·         Unchecked Exceptions are those which occur at runtime and need not be explicitly handled. RuntimeException and it's subclasses, Error and it's subclasses fall under unchecked exceptions.
·         A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses. Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream's read() method·
·         Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method· Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.
·         At compile time, the java compiler checks that a program contains handlers for checked exceptions. Java compiler analyzes by which checked exceptions can result from execution of a method or constructor.For each checked exception which is a possible result, the throws clause for the method or constructor must mention the class or its superclasses of that exception.
·         The class RuntimeException and its subclasses, and the class Error and its subclasses are unchecked exceptions classes. Because the compiler doesn’t forces them to be declared in the throws clause. All the other exception classes that are part of Throwable hierarchy are checked exceptions.

12) What are User defined Exceptions?
Apart from the exceptions already defined in Java package libraries, user can define his own exception classes by extending Exception class.
13)   
     Finally block will be executed whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement match the exception. Any time a method is about to return to the caller from inside try/catch block, via an uncaught exception or an explicit return statement, the finally block will be executed. Finally is used to free up resources like database connections, IO handles, etc.

14) Can a catch block exist without a try block?
No. A catch block should always go with a try block.

15) Can a finally block exist with a try block but without a catch?
Yes. The following are the combinations try/catch or try/catch/finally or try/finally.

16) What will happen to the Exception object after exception handling?
Exception object will be garbage collected.

17) The subclass exception should precede the base class exception when used within the catch clause. True/False?
True.
18) Exceptions can be caught or rethrown to a calling method. True/False?
True.
19) The statements following the throw keyword in a program are not executed. True/False?
True.

20) How does finally block differ from finalize() method?
Finally block will be executed whether or not an exception is thrown. So it is used to free resources. finalize() is a protected method in the Object class which is called by the JVM just before an object is garbage collected.

21) What are the constraints imposed by overriding on exception handling?
An overriding method in a subclass may only throw exceptions declared in the parent class or children of the exceptions declared in the parent class

22) What classes of exceptions may be caught by a catch clause?
A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types.

23) What class of exceptions are generated by the Java run-time system?
The Java runtime system generates RuntimeException and Error exceptions.

24) What happens if an exception is not caught?
An uncaught exception results in the uncaughtException() method of the thread's ThreadGroup being invoked, which eventually results in the termination of the program in which it is thrown.

25) Explain the user defined Exceptions?
User defined Exceptions are the separate Exception classes defined by the user for specific purposed. An user defined can created by simply sub-classing it to the Exception class. This allows custom exceptions to be generated (using throw) and caught in the same way as normal exceptions.
Example:
class myCustomException extends Exception {
// The class simply has to exist to be an exception
}

26) What are checked exceptions?
Checked exception are those which the Java compiler forces you to catch. e.g. IOException are checked Exceptions.

27) What are runtime exceptions?
Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time.

28) 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?
One can not do anything in this scenario. Because Java does not allow multiple inheritance and does not provide any exception interface as well.

29) How does a try statement determine which catch clause should be used to handle an exception?
When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exceptionis executed. The remaining catch clauses are ignored.

30) What is the catch or declare rule for method declarations?
If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause.

31) What is the relationship between a method's throws clause and the exceptions that can be thrown during the method's execution?
A method's throws clause must declare any checked exceptions that are not caught within the body of the method.

32) When a program does not want to handle exception, the ______class is used.
Ans : Throws
33) The main subclass of the Exception class is _______ class.
Ans : RuntimeException
34) Only subclasses of ______class may be caught or thrown.
Ans : Throwable
35) Any user-defined exception class is a subclass of the _____ class.
Ans : Exception
36) The catch clause of the user-defined exception class should ______ its Base class catch clause.
Ans : Exception
37) The finally block is executed when an exception is thrown, even if no catch matches it. True/False
Ans : True
38) The subclass exception should precede the base class exception when used within the catch clause. True/False
Ans : True
39) Exceptions can be caught or rethrown to a calling method.True/False
Ans : True
40) The statements following the throw keyword in a program are not executed.True/False
Ans : True
41) The toString ( ) method in the user-defined exception class is overridden.True/False
Ans : True
42) What is NullPointerException and how to handle it?
When an object is not initialized, the default value is null. When the following things happen, the NullPointerException is thrown:
--Calling the instance method of a null object.
--Accessing or modifying the field of a null object.
--Taking the length of a null as if it were an array.
--Accessing or modifying the slots of null as if it were an array.
--Throwing null as if it were a Throwable value.
The NullPointerException is a runtime exception. The best practice is to catch such exception even if it is not required by language design.

43) Can an unreachable object become reachable again?
An unreachable object may become reachable again. This can happen when the object's finalize() method is invoked and the object performs an operation which causes it to become accessible to reachable objects.

44) What are the different ways to handle exceptions?
There are two ways to handle exceptions,
1. By wrapping the desired code in a try block followed by a catch block to catch the exceptions. and
2. List the desired exceptions in the throws clause of the method and let the caller of the method handle those exceptions

45) Which of the following are true about the Error and Exception classes?
Both classes extend Throwable.
The Error class is final and the Exception class is not.
The Exception class is final and the Error is not.
Both classes implement Throwable.
Ans : a.

46) Assuming a method contains code which may raise an Exception (but not a RuntimeException), what is the correct way for a method to indicate that it expects the caller to handle that exception:
1) throw Exception
2) throws Exception
3) new Exception
4) Don't need to specify anything
Answer : 2
47) What is the result of executing the following code, using the parameters 4 and 0:
public void divide(int a, int b) {
try {
int c = a / b;
} catch (Exception e) {
System.out.print("Exception ");
} finally {
System.out.println("Finally");
}
1) Prints out: Exception Finally
2) Prints out: Finally
3) Prints out: Exception
4) No output
Answer : 1

 48) What is user-defined exception in java ?  

User-defined expections are the exceptions defined by the application developer which are errors related to specific application. Application Developer can define the user defined exception by inherite the Exception class as shown below. Using this class we can throw new exceptions. 
Java Example :
public class noFundException extends Exception { } Throw an exception using a throw statement: public class Fund { ... public Object getFunds() throws noFundException { if (Empty()) throw new noFundException(); ... } } User-defined exceptions should usually be checked.

49) What is the difference between checked and Unchecked Exceptions in Java ?
Answer: All predefined exceptions in Java are either a checked exception or an unchecked exception. Checked exceptions must be caught using try .. catch() block or we should throw the exception using throws clause. If you dont, compilation of program will fail.

50) What are Checked Exceptions and Unchecked Exceptions?

The types of exceptions that need not be included in a methods throws list are called Unchecked Exceptions.
ArithmeticException
ArrayIndexOutOfBoundsException
ClassCastException
IndexOutOfBoundsException
IllegalStateException
NullPointerException
SecurityException

The types of exceptions that must be included in a methods throws list if that method can generate one of these exceptions and does not handle it itself are called Checked Exceptions.
ClassNotFoundException
CloneNotSupportedException
IllegalAccessException
InstantiationException
InterruptedException
NoSuchFieldException
NoSuchMethodException
 

9) What are Checked Exceptions and Unchecked Exceptions?

The types of exceptions that need not be included in a methods throws list are called Unchecked Exceptions.
ArithmeticException
ArrayIndexOutOfBoundsException
ClassCastException
IndexOutOfBoundsException
IllegalStateException
NullPointerException
SecurityException

The types of exceptions that must be included in a methods throws list if that method can generate one of these exceptions and does not handle it itself are called Checked Exceptions.
ClassNotFoundException
CloneNotSupportedException
IllegalAccessException
InstantiationException
InterruptedException
NoSuchFieldException
NoSuchMethodException
 

No comments:

Post a Comment