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 runtime 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 runtime 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, it can have both blocks.
  • We can’t write any code between try-catch-finally 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.



Related Post :--
How to create the custom exception in Java?

24 comments:

  1. i had found necessary info here...gud 1

    ReplyDelete
  2. Thanks for comment...Keep visiting and happy coding.

    ReplyDelete
  3. I have read your blog its very attractive and impressive. I like it your blog.

    Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

    Java Online Training Java Online Training Core Java 8 Training in Chennai Core java 8 online training JavaEE Training in Chennai Java EE Training in Chennai

    ReplyDelete
  4. nice article...

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. Exception handling best practices refer this from Lokesh Gupta Top 20 Java Exception Handling Best Practices

    ReplyDelete
  7. Excellent Blog very imperative good content, this article is useful to beginners and real time Employees...Oracle Training in Chennai
    Oracle Training Institute in Chennai

    ReplyDelete
  8. That was a great message in my carrier, and It's wonderful commands like mind relaxes with understand words of knowledge by information's.

    java training in chennai | java training in bangalore

    java training in tambaram | java training in velachery

    java training in omr | oracle training in chennai

    ReplyDelete
  9. mytectra placement Portal is a Web based portal brings Potentials Employers and myTectra Candidates on a common platform for placement assistance.

    ReplyDelete
  10. Your very own commitment to getting the message throughout came to be rather powerful and have consistently enabled employees just like me to arrive at their desired goals.
    Python training in usa
    Python training in marathahalli
    Python training in pune

    ReplyDelete
  11. Great post! I am actually getting ready to across this information, It’s very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.
    DevOps online Training
    DevOps Training in USA

    ReplyDelete
  12. Your new valuable key points imply much a person like me and extremely more to my office workers. With thanks from every one of us.

    Best AWS Training in Chennai | Amazon Web Services Training in Chennai

    AWS Training in Bangalore | Amazon Web Services Training in Bangalore

    Amazon Web Services Training in Pune | Best AWS Training in Pune


    Your new valuable key points imply much a person like me and extremely more to my office workers. With thanks from every one of us.

    ReplyDelete
  13. Needed to compose you a very little word to thank you yet again regarding the nice suggestions you’ve contributed here.
    Blueprism training in Pune

    Blueprism training in Chennai

    ReplyDelete
  14. I believe there are many more pleasurable opportunities ahead for individuals that looked at your site.
    python training in tambaram
    python training in annanagar
    python training in jayanagar

    ReplyDelete
  15. This is most informative and also this post most user friendly and super navigation to all posts... Thank you so much for giving this information to me.. 
    Devops Training courses

    Devops Training in Bangalore

    Devops Training in pune

    ReplyDelete
  16. Does your blog have a contact page? I’m having problems locating it but, I’d like to shoot you an email. I’ve got some recommendations for your blog you might be interested in hearing.
    AWS Training in Chennai |Best Amazon Web Services Training in Chennai
    AWS Training in Rajaji Nagar | Amazon Web Services Training in Rajaji Nagar

    Best AWS Training Institute in BTM Layout Bangalore ,AWS Coursesin BTM

    ReplyDelete
  17. A really good post, it answers multiple questions that I had. Thanks a lot.aws online training

    ReplyDelete