Friday, July 5, 2013

Core Java Exception Interview Questions


     Exceptions Interview Questions

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

2. Exceptions are defined in which java package?

Ans. All the exceptions are subclasses of java.lang.Exception

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

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

5. Explain the exception hierarchy in java.
Ans. The hierarchy is as follows:




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.

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


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


Ans. The only difference between checked and unchecked exceptions is that checked ones have to be either caught or declared in the method signature using throws, whereas with unchecked ones this is optional.
Unchecked Exception can't be handled by your code i.e. we can't use try/catch block
Sure we can - but we don't have to.
Though error can be caught in catch block but the execution of application will come to a halt and is not recoverable.

Also I think throw keyword can be used only with try/catch block.

Note that there are two keywords:
  • throw explicitly throws an exception object you created. throw new NullPointerException();works perfectly fine, though explicitly creating that particular exception is uncommon and most would consider it bad style.
  • throws declares that a method may throw that exception. With unchecked exceptions this is optional, but can be useful to document the fact (again, one would normally not declared throws NullPointerException because that is pretty much a given).

Exp:

package com.sushil.exception;

public class ErrorTest {

       public static void main(String[] args) throws MyException {
              try {
                    
                     float f= 10/0;
                    
                     //throw new MyException();
                     throw new Error();
              } catch (Error e1) {
                     System.out.println("Errors " );

              }catch (RuntimeException e1) {
                     System.out.println("Runtime Exception " );
             
              }catch (Exception e1) {
                     System.out.println("Checked Exception " );
             
              }
       }
}

9. What is difference b/w 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.

10. 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");
            }
  }


11. 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 the throws 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.
  }

13. What are the possible combinations 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.

14. How to create custom Exception?

Ans) To create your own exception extend the Exception class or any of its subclasses.

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

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

16. What is StackOverflowError?

Ans. The StackOverFlowError is an Error Object thrown 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();

}

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

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

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

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

21. 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{
//some code throwing exception
}
String str = “ABC”;
System.out.println(“str = “+str);
catch(Exception e){}


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

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

24. Can you catch more than one exception 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.

JAVA 7:

catch (IOException|SQLException ex) {
    logger.log(ex);
}


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

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

27. What happens if the handler 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 (Exception e) {

// handles Exceptions of any types

} catch (IOException ex) {

// handle IOException 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
}


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

29. What happens if a method does not throw a 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();

}

30. 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 not get any information about the exception thrown.

try{

//code that may throw the FileNotFoundException

}catch(FileNotFound eFnf){

//no code to handle the FileNotFound exception

}

 31. Can a catch block throw the exception caught by itself?

Ans. Yes. This is called re-throwing of the exception by catch block.

e.g. the catch block below catches the FileNotFound exception and re-throws it again.

void checkEx() throws FileNotFoundException {

try{

//code that may throw the FileNotFoundException

}catch(FileNotFound eFnf){

throw FileNotFound();

}

}



32. What classes of exceptions may be caught by a catch clause?

Ans. A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types. Errors are generally irrecoverable conditions

33. What classes of exceptions are generated by the Java run-time system?

Ans. The Java runtime system generates Runtime Exceptions and Errors.



34. Does the code in finally block get executed if there is an exception and a return statement in a catch block?

Ans. The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught. If an exception occurs and there is a return statement in catch block, the finally block is still executed. The finally block will not be executed when the System.exit(0) statement is executed earlier or on system shut down earlier or the memory is used up earlier before the thread goes to finally block.

try{ //some statements }
catch{ //statements when exception is caught }
finally{ //statements executed whether exception occurs or not }



35. What happens if an uncaught exception is thrown from during the execution of the finalize() method of an object?

Ans. The exception will be ignored and the garbage collection (finalization) of that object terminates.



36. What will happen if an exception is thrown from the finally block?



Ans. The program will exit if the exception is not caught in the finally block.



37. If a method throws NullPointerException in super class, can we override it with a method which throws RuntimeException?

Ans. this questions is from overloading and overriding concept. you can very well throw super class of RuntimeException in overridden method but you can not do same if its checked Exception.




Note : Overriding method cannot throw higher Exception than original or overridden method means if original method throws IOException than overriding method cannot throw super class of IOException e.g. Exception but it can throw any sub class of IOException or simply does not throw any Exception. This rule only applies to checked Exception in Java, overridden method is free to throw any unchecked Exception.

38. What if there is a break or return statement in try block followed by finally block? 



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


39. Why Runtime Exceptions are Not Checked?

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



 


NOTE :-

Hibernate Exception:

 If we use hibernate session factory then it throw hibernate exception

Data Access Exception or Spring dao exception:

When we use spring abstraction like hibernate template then we throw Data Access exception



 


No comments: