JAVA INTERVIEW QUESTIONS - Exception Handling

Exception Handling

1) What is the difference between ‘throw’ and ‘throws'? And it’s application?
Ans: Exceptions that are thrown by Java runtime systems can be handled by Try and catch blocks. With throw exception, we can handle the exceptions thrown by the program itself. If a method is capable of causing an exception that it does not
handle, it must specify this behavior so the callers of the method can guard
against that exception.

2) What is the difference between ‘Exception’ and ‘error’ in java?
Ans: Exception and Error are the subclasses of the Throwable class. Exception class is used for exceptional conditions that user program should catch. With exception class, we can subclass to create our own custom exception.
Error defines exceptions that are not excepted to be caught by you program. An example is Stack Overflow.

3) What is ‘Resource leak’?
Ans: Freeing up other resources that might have been allocated at the beginning of a method.

4)What is the ‘finally’ block?
Ans: Finally block will execute 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 clause is also executed.

5) Can we have catch block without try block? If so when?
Ans: No. Try/Catch or Try/finally form a unit.

6) What will happen to the Exception object after exception handling?
Ans: It will go for Garbage Collector. And frees the memory.

7) How many Exceptions we can define in ‘throws’ clause?
Ans: We can define multiple exceptions in throws clause.
Signature is..
type method-name (parameter-list) throws exception-list

8) The finally block is executed when an exception is thrown, even if no catch matches it.
True/False
Ans: True

9) The subclass exception should precede the base class exception when used within the catch clause.
True/False
Ans: True

10) Exceptions can be caught or rethrown to a calling method.
True/False
Ans: True

11) The statements following the throw keyword in a program are not executed.
True/False
Ans: True

12) The toString ( ) method in the user-defined exception class is overridden.
True/False

Ans: True
Powered by Blogger.