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.

         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, 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?


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

                                      //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--
                                         //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(){
                                              //some statements
                                              return 1;
                                    catch(Exception e){
                                              return 2;
                                              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--
                                               int i=0; int j=1;
                                               int sum=j/i;                                             //line 1
                                               System.exit(0);                                      //line 2
                                        catch(Exception e){
                                                 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
                                               int sum=1/1;                                             //line 1
                                               System.exit(0);                                        //line 2
                                        catch(Exception e){
                                                System.out.println("finally block");

    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


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.

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?


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

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

  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

  4. nice article...

  5. This comment has been removed by the author.

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

  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

  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

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

  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

  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

  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.

  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

  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

  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

  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

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

  18. Good job in presenting the correct content with the clear explanation. The content looks real with valid information. Good Work

    DevOps is currently a popular model currently organizations all over the world moving towards to it. Your post gave a clear idea about knowing the DevOps model and its importance.

    Good to learn about DevOps at this time.

    devops training in chennai | devops training in chennai with placement | devops training in chennai omr | devops training in velachery | devops training in chennai tambaram | devops institutes in chennai | devops certification in chennai | trending technologies list 2018

  19. Amazon has a simple web services interface that you can use to store and retrieve any amount of data, at any time, from anywhere on the web. Amazon Web Services (AWS) is a secure cloud services platform, offering compute power, database storage, content delivery and other functionality to help businesses scale and grow.For more information visit.
    aws online training
    aws training in hyderabad
    aws online training in hyderabad