Tuesday 3 June 2014

Exception Handling Interview questions and answers


 Exception Handling Keywords:

                  Java provides specific keywords for exception handling purposes, we will look after them first and then we will write a simple program showing how to use them for exception handling.

  1throw 
          
         We know that if any exception occurs, an exception object is getting created and then Java run time starts processing to handle them. Sometime we might want to generate exception explicitly in our code, for example in a user authentication program we should throw exception to client if the password is null. throw keyword is used to throw exception to the run time to handle it.


   2. throws

               When we are throwing any exception in a method and not handling it, then we need to use throws keyword in method signature to let caller program know the exceptions that might be thrown by the method. The caller method might handle these exceptions or propagate it to it’s caller method using throws keyword. We can provide multiple exceptions in the throws clause and it can be used with main() method also.


  3. try-catch
           
          We use try-catch block for exception handling in our code. try is the start of the block and catch is at the end of try block to handle the exceptions. We can have multiple catch blocks with a try and try-catch block can be nested also. catch block requires a parameter that should be of type Exception.


  4. finally

        finally block is optional and can be used only with try-catch block. Since exception halts the process of execution, we might have some resources open that will not get closed, so we can use finally block. finally block gets executed always, whether exception occurred or not.

   
Look at following important points:-  
  • We can’t have catch or finally clause without a try statement.
  • A try statement should have either catch block or finally block or it can have both blocks.
  • We can’t write any code between try-catch-finally block. Will give compile time error ex if you write any statement between try and catch block.
  • We can have multiple catch blocks with a single try statement.
  • try-catch blocks can be nested similar to if-else statements.
  • We can have only one finally block with a try-catch statement.

      Below some questions related to try catch and finally block examples.

1) Which is the base class of all Exception classes?

            Throwable


2) Once the control switches to the catch block does it return   back to the try block to execute the balance code?
   
      No. Once the control jumps to the catch block it never returns to the try block but it goes to finally block(if present).


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

       All the exceptions inherit a method printStackTrace() from the Throwable class. This method prints the stack trace from where the exception occurred.
   e.g       catch(Exception e){
                     Systom.out.println(e.printStackTrace());
               }


4) 
                          try{                      
                                      //some statements
                               }
                               catch(Exception e){                 
                                      System.out.println("Exception ");
                               }
                               catch(ArithmeticExcetion ex){
                                      System.out.println("AritmeticException ");
                               }
what is output?

        It will give the compile-time error at second catch block. Exception is the base class of all Checked and Unchecked Exception so ArithmeticException is the base class of Exception.
So always you can write Exception catch block at the end.


5) See below code--
                              try{
                                         //some statements
                              }                                                                        //line 1
                              System.out.println("end try block");
                              catch(Exception e){                                              //line 2
                                       System.out.println("Exception ");
                              }

   It will give compile-time error at line 1 and line 2 because for first line you haven't written catch or finally block & second it act as without try block.


6) check it below code
                           public int methodName(){
                                    try{
                                              //some statements
                                              return 1;
                                    }
                                    catch(Exception e){
                                              return 2;
                                    }
                                    finally{
                                              return 3;
                                    }
                          }                                               //end method
    The above method will return which value 1 or 2 or 3. also answer me with exception & without exception.

     In java finally block will execute all time except calling System.exit(). So above example it will return always 3 with exception or non-exception(not a matter).




7) see below code--
                                       try{
                                               int i=0; int j=1;
                                               int sum=j/i;                                             //line 1
                                               System.exit(0);                                      //line 2
                                        }
                                        catch(Exception e){
                                                e.printStackTrace();
                                        }
                                        finally{
                                                 System.out.println("finally block");
                                        }
 what would be the output?finally block will execute or not?

 Output is----------------java.lang.ArithmeticException
                                                   finally block

In the above code,at line 1,it will throw exception i.e catch block will execute and followed by finaaly block execute. It never return to the line 2.





8) In the above code,if there is no exception at line 1,then
                                        try{
                                               int sum=1/1;                                             //line 1
                                               System.out.println(sum);
                                               System.exit(0);                                        //line 2
                                        }
                                        catch(Exception e){
                                                e.printStackTrace();
                                        }
                                        finally{
                                                System.out.println("finally block");
                                        }
output?

    In the above code finally block won't execute because it will exit in try block itself.
               output is 1.
   

9) Exception Hierarchy in java


exceptionhierarchy

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.
 
Exception :
        
         An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. There are two types of Exceptions 1)Checked Exception 2) Unchecked Exception

1) Checked Exception:--

              These exceptions are the object of the Exception class or any of its subclasses except Runtime exception class.  These condition arises due to invalid input,problem with your network connectivity & problem in database. IOException,SQLException,DataAccessException,ClassNotFoundException & MalformedURLException are the Checked Exception.  This Exception is thrown when there is an error in I/O operation. In this case operation is normally terminated.

2) Unchecked Exception:--  

              These exceptions arises during run-time that occur due to invalid argument passed to method. The java compiler doesn't check the program error during compilation. e.g ArithmeticException, NumberFormatException, NullPointerException, IndexOutOfBoundsException, ClassCastException & IllegalArgumentException etc.
             


Does method can return exception ?

     Method does not return exception but it will throw an exception.


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


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 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. For more details, Refer Difference between NoClassDefFoundError and ClassNotFoundException in Java



Related Post :--
1) How to create the custom exception in Java?
2) String Interview Questions and Answers
3) Difference between final,finalize and finally in Java
4) Exception Handling in method overriding in Java
5) Static Keyword and Its usage in Java
6) Factory Design Pattern in Java
7) Difference between NoClassDefFoundError and ClassNotFoundException in Java

7 comments: