Tuesday 25 June 2013

Exception Handling


JAVA EXCEPTION HANDLING INTERVIEW QUESTIONS AND ANSWERS


Exceptions Interview Questions

Q1) What is an Exception?
Ans) The exception is said to be thrown whenever an exceptional event occurs in java which signals that something is not correct with the code written and may give unexpected result. An exceptional event is a occurrence of condition which alters the normal program flow. Exceptional handler is the code that does something about the exception.
Q2) Exceptions are defined in which java package?
Ans)All the exceptions are subclasses of java.lang.Exception
Q3) How are the exceptions handled in java?
Ans)When an exception occurs the execution of the program is transferred to an appropriate exception handler.The try-catch-finally block is used to handle the exception.
The code in which the exception may occur is enclosed in a try block, also called as a guarded region.
The catch clause matches a specific exception to a block of code which handles that exception.
And the clean up code which needs to be executed no matter the exception occurs or not is put inside the finally block
Q4) Explain the exception hierarchy in java.
Ans) The hierarchy is as follows:
Exception
Throwable is a parent class off all Exception classes. They are two types of Exceptions: Checked exceptions and UncheckedExceptions. Both type of exceptions extends Exception class.
Q5) What is Runtime Exception or unchecked exception?
Ans) Runtime exceptions represent problems that are the result of a programming problem. Such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small. Runtime exceptions need not be explicitly caught in try catch block as it can occur anywhere in a program, and in a typical one they can be very numerous. Having to add runtime exceptions in every method declaration would reduce a program's clarity. Thus, the compiler does not require that you catch or specify runtime exceptions (although you can). The solution to rectify is to correct the programming logic where the exception has occurred or provide a check.
Q6) What is checked exception?
Ans) Checked exception are the exceptions which forces the programmer to catch them explicitly in try-catch block. It is a subClass of Exception. Example: IOException.
Q7) What is difference between Error and Exception?
Ans) An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime.Though error can be caught in catch block but the execution of application will come to a halt and is not recoverable.
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.)
Q8) What is difference between ClassNotFoundException and NoClassDefFoundError?
Ans) A ClassNotFoundException is thrown when the reported class is not found by the ClassLoader in the CLASSPATH. It could also mean that the class in question is trying to be loaded from another class which was loaded in a parent classloader and hence the class from the child classloader is not visible.
Consider if NoClassDefFoundError occurs which is something like
java.lang.NoClassDefFoundError
src/com/TestClass
does not mean that the TestClass class is not in the CLASSPATH. It means that the class TestClass was found by the ClassLoader however when trying to load the class, it ran into an error reading the class definition. This typically happens when the class in question has static blocks or members which use a Class that's not found by the ClassLoader. So to find the culprit, view the source of the class in question (TestClass in this case) and look for code using static blocks or static members.
Q9) What is throw keyword?

Ans) Throw keyword is used to throw the exception manually. It is mainly used when the program fails to satisfy the given condition and it wants to warn the application.The exception thrown should be subclass of Throwable.
  public void parent(){
  try{
   child();
  }catch(MyCustomException e){ }
  }


  public void child{
  String iAmMandatory=null;
   if(iAmMandatory == null){
    throw (new MyCustomException("Throwing exception using throw keyword");
   }
  }
Q10) What is use of throws keyword?
Ans) If the function is not capable of handling the exception then it can ask the calling method to handle it by simply putting thethrows clause at the function declaration.
  public void parent(){
  try{
   child();
  }catch(MyCustomException e){ }
  }


  public void child throws MyCustomException{
   //put some logic so that the exception occurs.
  }
Q11) What are the possible combination to write try, catch finally block?
Ans)
1) try{
//lines of code that may throw an exception
}catch(Exception e){
//lines of code to handle the exception thrown in try block
}finally{
//the clean code which is executed always no matter the exception occurs or not.
}

2 try{
}finally{}
3 try{
}catch(Exception e){
//lines of code to handle the exception thrown in try block
}

The catch blocks must always follow the try block. If there are more than one catch blocks they all must follow each other without any block in between. The finally block must follow the catch block if one is present or if the catch block is absent the finally block must follow the try block.
Q12) How to create custom Exception?
Ans) To create you own exception extend the Exception class or any of its subclasses.
e.g.
1 class New1Exception extends Exception { } // this will create Checked Exception
2 class NewException extends IOExcpetion { } // this will create Checked exception
3 class NewException extends NullPonterExcpetion { } // this will create UnChecked exception

Q13) When to make a custom checked Exception or custom unchecked Exception?

Ans) If an application can reasonably be expected to recover from an exception, make it a checked exception. If an application cannot do anything to recover from the exception, make it an unchecked exception.
Q14)What is StackOverflowError?
Ans) The StackOverFlowError is an Error Object thorwn by the Runtime System when it Encounters that your application/code has ran out of the memory. It may occur in case of recursive methods or a large amount of data is fetched from the server and stored in some object. This error is generated by JVM.
e.g. void swap(){
swap();
}
Q15) Why did the designers decide to force a method to specify all uncaught checked exceptions that can be thrown within its scope?
Ans) Any Exception that can be thrown by a method is part of the method's public programming interface. Those who call a method must know about the exceptions that a method can throw so that they can decide what to do about them. These exceptions are as much a part of that method's programming interface as its parameters and return value.
Q16) Once the control switches to the catch block does it return back to the try block to execute the balance code?
Ans) No. Once the control jumps to the catch block it never returns to the try block but it goes to finally block(if present).
Q17) Where is the clean up code like release of resources is put in try-catch-finally block and why?
Ans) The code is put in a finally block because irrespective of try or catch block execution the control will flow to finally block. Typically finally block contains release of connections, closing of result set etc.
Q18) Is it valid to have a try block without catch or finally?
Ans) NO. This will result in a compilation error. The try block must be followed by a catch or a finally block. It is legal to omit the either catch or the finally block but not both.
e.g. The following code is illegal.
try{
int i =0;
}
int a = 2;
System.out.println(“a = “+a);

Q19) Is it valid to place some code in between try the catch/finally block that follows it?

Ans) No. There should not be any line of code present between the try and the catch/finally block. e.g. The following code is wrong.
try{}
String str = “ABC”;
System.out.println(“str = “+str);
catch(Exception e){}

Q20) What happens if the exception is never caught and throws down the method stack?

Ans) If the exception is not caught by any of the method in the method’s stack till you get to the main() method, the main method throws that exception and the JVM halts its execution.

Q21) How do you get the descriptive information about the Exception occurred during the program execution?

Ans) All the exceptions inherit a method printStackTrace() from the Throwable class. This method prints the stack trace from where the exception occurred. It prints the most recently entered method first and continues down, printing the name of each method as it works its way down the call stack from the top.
Q22) Can you catch more than one exceptions in a single catch block?
Ans)Yes. If the exception class specified in the catch clause has subclasses, any exception object that is a subclass of the specified Exception class will be caught by that single catch block.
E.g..
try {
// Some code here that can throw an IOException
}
catch (IOException e) {
e.printStackTrace();
}
The catch block above will catch IOException and all its subclasses e.g. FileNotFoundException etc.
Q23)Why is not considered as a good practice to write a single catchall handler to catch all the exceptions?
Ans) You can write a single catch block to handle all the exceptions thrown during the program execution as follows :
try {
// code that can throw exception of any possible type
}catch (Exception e) {
e.printStackTrace();
}
If you use the Superclass Exception in the catch block then you will not get the valuable information about each of the exception thrown during the execution, though you can find out the class of the exception occurred. Also it will reduce the readability of the code as the programmer will not understand what is the exact reason for putting the try-catch block.
Q24) What is exception matching?
Ans) Exception matching is the process by which the the jvm finds out the matching catch block for the exception thrown from the list of catch blocks. When an exception is thrown, Java will try to find by looking at the available catch clauses in the top down manner. If it doesn't find one, it will search for a handler for a supertype of the exception. If it does not find a catch clause that matches a supertype for the exception, then the exception is propagated down the call stack. This process is called exception matching.
Q25) What happens if the handlers for the most specific exceptions is placed above the more general exceptions handler?
Ans) Compilation fails. The catch block for handling the most specific exceptions must always be placed above the catch block written to handle the more general exceptions.
e.g. The code below will not compile.
1 try {
// code that can throw IOException or its subtypes
} catch (IOException e) {
// handles IOExceptions and its subtypes
} catch (FileNotFoundException ex) {
// handle FileNotFoundException only
}
The code below will compile successfully :-
try {
// code that can throw IOException or its subtypes
} catch (FileNotFoundException ex) {
// handles IOExceptions and its subtypes
} catch (IOException e){
// handle FileNotFoundException only

Q26) Does the order of the catch blocks matter if the Exceptions caught by them are not subtype or supertype of each other?

Ans) No. If the exceptions are siblings in the Exception class’s hierarchy i.e. If one Exception class is not a subtype or supertype of the other, then the order in which their handlers(catch clauses) are placed does not matter.
Q27) What happens if a method does not throw an checked Exception directly but calls a method that does? What does 'Ducking' the exception mean?
Ans) If a method does not throw an checked Exception directly but calls a method that throws an exception then the calling method must handle the throw exception or declare the exception in its throws clause. If the calling method does not handle and declares the exception, the exceptions is passed to the next method in the method stack. This is called as ducking the exception down the method stack.
e.g. The code below will not compile as the getCar() method has not declared the CarNotFoundException which is thrown by the getColor () method.
void getCar() {
getColor();
}
void getColor () {
throw new CarNotFoundException();
}
Fix for the above code is
void getCar() throws CarNotFoundException {
getColor();
}
void getColor () {
throw new CarNotFoundException();
}

Q28) Is an empty catch block legal?

Ans) Yes you can leave the catch block without writing any actual code to handle the exception caught.
e.g. The code below is legal but not appropriate, as in this case you will nt get any information about the exception thrown.
try{
//code that may throw the FileNotFoundException
}catch(FileNotFound eFnf){
//no code to handle the FileNotFound exception
}

Q29)Can a catch block throw the exception caught by itself?
Ans) Yes. This is called rethrowing of the exception by catch block.
e.g. the catch block below catches the FileNotFound exception and rethrows it again.
void checkEx() throws FileNotFoundException {
try{
//code that may throw the FileNotFoundException
}catch(FileNotFound eFnf){
throw FileNotFound();
}
}


JAVA EXCEPTION HANDLING INTERVIEW QUESTIONS AND ANSWERS
1) Which package contains exception handling related classes?
java.lang

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

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

4) 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.

5) What is the difference between throw and throws?
throw is used to explicitly raise a 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{}

6) Differentiate between Checked Exceptions and Unchecked Exceptions?
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.

7) 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.

8) What is the importance of finally block in exception handling?
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.

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

10) 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.

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

12) The subclass exception should precede the base class exception when used within the catch clause. True/False?
True.

13) Exceptions can be caught or rethrown to a calling method. True/False?
True.

14) The statements following the throw keyword in a program are not executed. True/False?
True.

15) 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 resoources. finalize() is a protected method in the Object class which is called by the JVM just before an object is garbage collected.

16) 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. 
******************************************************************************************************************1.What is an exception?

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.
2.What is error?
An Error indicates that a non-recoverable condition has occurred that should not be caught. Error, a subclass of Throwable, is intended for drastic problems, such as OutOfMemoryError, which would be reported by the JVM itself.
3.Which is superclass of Exception?
"Throwable", the parent class of all exception related classes.
4.What are the advantages of using exception handling?
Exception handling provides the following advantages over "traditional" error management techniques:
  • Separating Error Handling Code from "Regular" Code.
  • Propagating Errors Up the Call Stack.
  • Grouping Error Types and Error Differentiation.
5.What are the types of Exceptions in Java
There are two types of exceptions in Java, unchecked exceptions and checked exceptions.
  • Checked exceptions: A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses. Each method must either handle all checked exceptions by supplying a catch clause or list each unhandled checked exception as a thrown exception.
  • Unchecked exceptions: All Exceptions that extend the RuntimeException class are unchecked exceptions. Class Error and its subclasses also are unchecked.
6.Why Errors are Not Checked?
A unchecked exception classes which are the error classes (Error and its subclasses) are exempted from compile-time checking because they can occur at many points in the program and recovery from them is difficult or impossible. A program declaring such exceptions would be pointlessly.

7.Why Runtime Exceptions are Not Checked?
The runtime exception classes (RuntimeException and its subclasses) are exempted from compile-time checking because, in the judgment of the designers of the Java programming language, having to declare such exceptions would not aid significantly in establishing the correctness of programs. Many of the operations and constructs of the Java programming language can result in runtime exceptions. The information available to a compiler, and the level of analysis the compiler performs, are usually not sufficient to establish that such run-time exceptions cannot occur, even though this may be obvious to the programmer. Requiring such exception classes to be declared would simply be an irritation to programmers.

8.Explain the significance of try-catch blocks?
Whenever the exception occurs in Java, we need a way to tell the JVM what code to execute. To do this, we use the try and catch keywords. The try is used to define a block of code in which exceptions may occur. One or more catch clauses match a specific exception to a block of code that handles it.

Try-Catch-Finally

9.What is the use of finally block?

The finally block encloses code that is always executed at some point after the try block, whether an exception was thrown or not. This is right place to close files, release your network sockets, connections, and perform any other cleanup your code requires.

Note: If the try block executes with no exceptions, the finally block is executed immediately after the try block completes. It there was an exception thrown, the finally block executes immediately after the proper catch block completes

10.What if there is a break or return statement in try block followed by finally block?
If there is a return statement in the try block, the finally block executes right after the return statement encountered, and before the return executes.
******************************************************************************************************************
Can we have the try block without catch block?
Yes, we can have the try block without catch block, but finally block should follow the try block.
Note: It is not valid to use a try clause without either a catch clause or a finally clause.

12.What is the difference throw and throws?
throws: Used in a method's signature if a method is capable of causing an exception that it does not handle, so that callers of the method can guard themselves against that exception. If a method is declared as throwing a particular class of exceptions, then any other method that calls it must either have a try-catch clause to handle that exception or must be declared to throw that exception (or its superclass) itself.


A method that does not handle an exception it throws has to announce this:
  public void myfunc(int arg) throws MyException {
        …
    }
throw: Used to trigger an exception. The exception will be caught by the nearest try-catch clause that can catch that type of exception. The flow of execution stops immediately after the throw statement; any subsequent statements are not executed.


To throw an user-defined exception within a block, we use the throw command:
  throw new MyException("I always wanted to throw an exception!");
13.How to create custom exceptions?
A. By extending the Exception class or one of its subclasses.
Example:
class MyException extends Exception {
  public MyException() { super(); }
  public MyException(String s) { super(s); }
  }
14.What are the different ways to handle exceptions?
There are two ways to handle exceptions:
  • Wrapping the desired code in a try block followed by a catch block to catch the exceptions.
  • List the desired exceptions in the throws clause of the method and let the caller of the method handle those exceptions.














1. What is an exception and an error ?


Exception :

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.

Error : 

An Error indicates that a non-recoverable condition has occurred that should not be caught. Error, a subclass of Throwable, is intended for drastic problems, such asOutOfMemoryError, which would be reported by the JVM itself.
__________________________________________________________
  
2. What are the advantages of using exception handling ?


Exception handling provides the following advantages over "traditional" error management techniques:
  1. Separating Error Handling Code from "Regular" Code.
  2. Propagating Errors Up the Call Stack.
  3. Grouping Error Types and Error Differentiation.
__________________________________________________________
  
3. What is the difference between Validation, Exception and Error ?


Validation is the process of making user enter data in a format which the application can handle.
Exception handling is the process when the application logic didn’t work as expected by the Java compiler.

Error occurs in a situation where the normal application execution can not continue. For e.g. out of memory.
__________________________________________________________
  
4. What is the difference between checked and unchecked exception handling in Java ?


Checked exceptions are the one for which there is a check by the compiler that these exceptions have to be caught or specified with throws keyword. These kind of exceptions occur because of conditions which are out of control of the application like Network error, File Access Denied etc.

Unchecked exceptions are the one which arise because of logic written by the developer. e.g. Trying to access an array element which doesn’t exist.

__________________________________________________________


5. Why Run time Exceptions are Not Checked ?



Java provides two main exception types: runtime exceptions and checked exceptions. All checked exceptions extend from java.lang.Exception, while runtime exceptions extend from either java.lang.RuntimeException or java.lang.Error.

For Run time exceptions :
  • method signature does not need to declare runtime exceptions
  • caller to a method that throws a runtime exception is not forced to catch the runtime exception
  • Runtime exceptions extend from RuntimeException or Error
For Checked exceptions :
  • method must declare each checked exception it throws
  • caller to a method that throws a checked exception must either catch the exception or throw the exception itself
  • Checked exceptions extend from Exception
Checked exceptions indicate an exceptional condition from which a caller can conceivably recover. Runtime exceptions indicate a programmatic error from which a caller cannot normally recover.

Checked exceptions force you to catch the exception and to do something about it. You should always catch a checked exception once you reach a point where your code can make a meaningful attempt at recovery. However, it is best not to catch runtime exceptions. Instead, you should allow runtime exceptions to bubble up to where you can see them.

In order to throw exeption from static block, you have to change MyException to inherit from RuntimeException. In my opinion, this is still not a elegant way.


6. When do you use a catch block and when do you use a finally block ?

We use a catch block when we want to handle the exception scenario. We use a finally block alone when we want to do some cleanup but at the same time propagate the exception to the caller. We use a finally block together with a catch block when we want to do something irrespective of what exception is thrown.

 __________________________________________________________
  
7. What are the differences between NoClassDefFoundError and ClassNotFoundException ?

NoClassDefFoundError occurs when a class was found during compilation but could not be located in the classpath while executing the program.
For example: class A invokes method from class B and both compile fine but before executing the program, an ANT script deleted B.class by mistake. Now on executing the program NoClassDefFoundError is thrown.

ClassNotFoundException occurs when a class is not found while dynamically loading a class using the class loaders.

For example: The database driver is not found when trying to load the driver using Class.forName() method.
__________________________________________________________
  
8. What is the purpose of finally block? In which scenario, the code in finally block will not be executed ?

Finally block is used to execute code which should be executed irrespective of whether an exception occurs or not. The kind of code written in a finally block consists of clean up code such as closing of database/file connection.

__________________________________________________________
  
9. Explain try and catch statements in Java ?


The try/catch statement encloses some code and is used to handle errors and exceptions that might occur in that code. Here is the general syntax of the try/catch statement:
try {
    body-code
} catch (exception-classname variable-name) {
    handler-code
}
The try/catch statement has four parts. The body-code contains code that might throw the exception that we want to handle. The exception-classname is the class name of the exception we want to handle. The variable-name specifies a name for a variable that will hold the exception object if the exception occurs. Finally, the handler-code contains the code to execute if the exception occurs. After the handler-code executes, execution of the thread continues after the try/catch statement. Here is an example of code that tries to create a file in a non-existent directory which results in an IOException.

__________________________________________________________


10. Can we have a try block without a catch block ?


Yes, then we must have a finally block. When try block is used, we must use either a catch block or a finally block or both



Custom exceptions are useful when the JDK exception classes don’t capture the essence of erroneous situation which has come up in the application. A custom exception can be created by extending any subclass of Exception class or by implementing Throwable interface.



16. If the overridden method in super class A throws FileNotFoundException, then the overriding method present in class B which is a subclass of class A can throw IOException. If the above statement true ?
The overriding method can not throw any checked exception other than the exception classes or sub-classes of those classes which are thrown by the overridden method.

In the scenario described in question, the method in class B can not throw IOException but can throw FileNotFoundException exception.
__________________________________________________________
  
17. What is the difference between checked and unchecked exception handling in Java ? What are the disadvantages of checked exception handling ?

Checked exceptions are the one for which there is a check by the compiler that these exceptions have to be caught or specified with throws keyword. These kind of exceptions occur because of conditions which are out of control of the application like Network error, File Access Denied etc.

Unchecked exceptions are the one which arise because of logic written by the developer. e.g. Trying to access an array element which doesn’t exist.

__________________________________________________________
  
18. If there is common code to be executed  in the catch block of 10 exceptions which are thrown from a single try block, then how that common code can be written with minimum effort ?

In pre JDK 7, a method can be written and all catch blocks can invoke this method containing the common code.

In JDK 7, the | operator can be used in catch block in order to execute common code for multiple exceptions. 
Example: 
catch(SQLException sqle | IOException ioe)
{
}
__________________________________________________________
  
19. Have you every created custom exceptions? Explain the scenario ?

Custom exceptions are useful when the JDK exception classes don’t capture the essence of erroneous situation which has come up in the application. A custom exception can be created by extending any subclass of Exception class or by implementing Throwable interface.

Example
: A custom exception can be thrown when the custom JSP tag has value for the attribute which is not expected.

__________________________________________________________

20. Can a catch block exist without a try block ?


No. A catch block should always go with a try block.

What will happen to the Exception object after exception handling ?

Exception object will be garbage collected. __________________________________________________________
  
22. Exceptions can be caught or rethrown to a calling method. True/False ?

True
 __________________________________________________________
  
23. 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.
__________________________________________________________
  
24. The statements following the throw keyword in a program are not executed. True/False ?

True.
_________________________________________________________

_

25. Can an exception be rethrown ?
Yes, an exception can be rethrown any number of times.


###############################################################


Exception Handling Interview Questions

February 13, 2009


1) What is an Exception?

An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error.

2) What is a Java Exception?

A Java exception is an object that describes an exceptional condition i.e., an error condition that has occurred in a piece of code. When this type of condition arises, an object representing that exception is created and thrown in the method that caused the error by the Java Runtime. That method may choose to handle the exception itself, or pass it on. Either way, at some point, the exception is caught and processed.

3) What are the different ways to generate and Exception?

There are two different ways to generate an Exception.
    1. Exceptions can be generated by the Java run-time system.
Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java language or the constraints of the Java execution environment.
    1. Exceptions can be manually generated by your code.
Manually generated exceptions are typically used to report some error condition to the caller of a method.

4) Where does Exception stand in the Java tree hierarchy?

  • java.lang.Object
  • java.lang.Throwable
  • java.lang.Exception
  • java.lang.Error

5) Is it compulsory to use the finally block?

It is always a good practice to use the finally block. The reason for using the finally block is, any unreleased resources can be released and the memory can be freed. For example while closing a connection object an exception has occurred. In finally block we can close that object. Coming to the question, you can omit the finally block when there is a catch block associated with that try block. A try block should have at least a catch or a finally block.

6) How are try, catch and finally block organized?

A try block should associate with at least a catch or a finally block. The sequence of try, catch and finally matters a lot. If you modify the order of these then the code won’t compile. Adding to this there can be multiple catch blocks associated with a try block. The final concept is there should be a single try, multiple catch blocks and a single finally block in a try-catch-finally block.

7) What is a throw in an Exception block?

“throw” is used to manually throw an exception (object) of type Throwable class or a subclass ofThrowable. Simple types, such as int or char, as well as non-Throwable classes, such as Stringand Object, cannot be used as exceptions. The flow of execution stops immediately after the throwstatement; any subsequent statements are not executed.
 throw ThrowableInstance; ThrowableInstance must be an object of type Throwable or a subclass of Throwable. throw new NullPointerException("thrownException"); 

8) What is the use of throws keyword?

If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception. You do this by including athrows clause in the method’s declaration. A throws clause lists the types of exceptions that a method might throw.
 type method-name(parameter-list) throws exception-list { // body of method } Warning: main(http://www.javabeat.net/javabeat/templates/faqs/faqs_middle.html): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in /home/content/k/k/s/kkskrishna/html/faqs/exception/exception-faqs-1.html on line 195 Warning: main(http://www.javabeat.net/javabeat/templates/faqs/faqs_middle.html): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in /home/content/k/k/s/kkskrishna/html/faqs/exception/exception-faqs-1.html on line 195 Warning: main(): Failed opening 'http://www.javabeat.net/javabeat/templates/faqs/faqs_middle.html' for inclusion (include_path='.:/usr/local/lib/php') in /home/content/k/k/s/kkskrishna/html/faqs/exception/exception-faqs-1.html on line 195 Here, exception-list is a comma-separated list of the exceptions that a method can throw. static void throwOne() throws IllegalAccessException { System.out.println("Inside throwOne."); 

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

10) What are Chained Exceptions?

The chained exception feature allows you to associate another exception with an exception. This second exception describes the cause of the first exception. Lets take a simple example. You are trying to read a number from the disk and using it to divide a number. Think the method throws anArithmeticException because of an attempt to divide by zero (number we got). However, the problem was that an I/O error occurred, which caused the divisor to be set improperly (set to zero). Although the method must certainly throw an ArithmeticException, since that is the error that occurred, you might also want to let the calling code know that the underlying cause was an I/O error. This is the place where chained exceptions come in to picture.
 Throwable getCause( ) Throwable initCause(Throwable causeExc) 


10 Exception Handling Interview Questions for Java

1) If the overridden method in super class A throws FileNotFoundException, then the overriding method present in class B which is a subclass of class A can throw IOException. If the above statement true?
Ans: The overriding method can not throw any checked exception other than the exception classes or sub-classes of those classes which are thrown by the overridden method.
 
In the scenario described in question, the method in class B can not throw IOException but can throw FileNotFoundException exception.
 
2) What is the difference between checked and unchecked exception handling in Java? What are the disadvantages of checked exception handling?
Ans: Checked exceptions are the one for which there is a check by the compiler that these exceptions have to be caught or specified with throws keyword. These kind of exceptions occur because of conditions which are out of control of the application like Network error, File Access Denied etc.
 
Unchecked exceptions are the one which arise because of logic written by the developer. e.g. Trying to access an array element which doesn’t exist.
 
3) If there is common code to be executed  in the catch block of 10 exceptions which are thrown from a single try block, then how that common code can be written with minimum effort?
 
Ans: In pre JDK 7, a method can be written and all catch blocks can invoke this method containing the common code.
 
In JDK 7, the | operator can be used in catch block in order to execute common code for multiple exceptions. e.g. catch(SQLException sqle | IOException ioe){}
 
4) Have you every created custom exceptions? Explain the scenario?
 
Ans: Custom exceptions are useful when the JDK exception classes don’t capture the essence of erroneous situation which has come up in the application. A custom exception can be created by extending any subclass of Exception class or by implementing Throwable interface.
 
E.g. A custom exception can be thrown when the custom JSP tag has value for the attribute which is not expected.
 
5) What is the difference between Validation, Exception and Error?
Ans: Validation is the process of making user enter data in a format which the application can handle.
 
Exception handling is the process when the application logic didn’t work as expected by the Java compiler.
 
Error occurs in a situation where the normal application execution can not continue. For e.g. out of memory.
 
6) What is the purpose of finally block? In which scenario, the code in finally block will not be executed?
 
Ans: finally block is used to execute code which should be executed irrespective of whether an exception occurs or not. The kind of code written in a finally block consists of clean up code such as closing of database/file connection.
 
But JDK 7 has come up with try with resources block which automatically handles the closing of resources.
 
7) What do you understand by Exception chaining?
Ans: I have written a blog post for this answer here
 
8) How will you make the client code to be transparent from business logic exceptions?
Ans: The use of Business Delegate design pattern makes the client invisible from business logic exceptions. This helps in decoupling the client from server which helps in better maintainability of the application in terms of future changes in client or business logic code.
 
9) What are the differences between NoClassDefFoundError and ClassNotFoundException?
 
Ans: NoClassDefFoundError occurs when a class was found during compilation but could not be located in the classpath while executing the program.
 
For example: class A invokes method from class B and both compile fine but before executing the program, an ANT script deleted B.class by mistake. Now on executing the program NoClassDefFoundError is thrown.
 
ClassNotFoundException occurs when a class is not found while dynamically loading a class using the class loaders.
 
For example: The database driver is not found when trying to load the driver using Class.forName() method.
 
10) What is the purpose of throw keyword? What happens if we write “throw null;” statement in a Java program?
 
Ans: ”throw” keyword is used to re-throw an exception which has been caught in a catch block. The syntax is “throw e;” where e is the reference to the exception being caught. The exception is re-thrown to the client.
 
This keyword is useful when some part of the exception is to be handled by the caller of the method in which throw keyword is used.
 
The use of “throw null;” statement causes NullPointerException to be thrown.
The answers are brief. Do post your comments if you think I have missed anything or discuss any other exception handling question.

Exception    Throwable is base class of Exception
  Checked Exception CompileTime - Compiler Dedect this Exception
  ClassNotFoundException  
  CloneNotSupportedException Java.io
  IllegalAccessException IOException
  InstantiationException EOFException
  InterruptedException FileNotFoundException
  NoSuchFieldException  
  NoSuchMethodException  
     
     
     
  UnCheckedException RunTime Exception (Caused By Programmer)
     
    NullPointerException
    ClassCastException
    AirthMathicException
    IllegalArrgumentException
    NumberFormatException
    IndexOutofBoundException
    ArrayIndexOutofBoundException
    StringIndexOutOfBoundException
     
  Custom Exception To create Custome exception need to extends Exception class or SubClass.
     
     
     
     
     
  Throw Throw keyword is used to throw the exception manually
  Throws When a method want to handle list of exception then used the throws Statement , Calling method is handle all the method level exception 
     
     
  Exception Chaining  
     
     
     
     
     
     
JDK-7    
  Resource Block Insteed of Finally we can Use the Resource Block
    In pre JDK 7, a method can be written and all catch blocks can invoke this method containing the common code

No comments:

Post a Comment