Java interview questions on exception handling.

Part 2

Java interview questions on exception handling covered in this post:


    Java interview questions on exception handling.

        Can we create a custom exception class? If yes then what are the steps to create a custom exception class?

    -          Yes we can create a custom exception class.

    -          Please follow the following steps to create your custom exception.

    1.       Create one Custom class and extends the Exception class.

    2.   Create one String type local variable and assign your custom message to that variable.

    3.      Pass the custom message in the Custom class constructor while instantiating the custom class.

    4.       Override toString() method to print the custom message.

    5.       We can simply throw a custom exception in any method and pass a custom message while creating a custom object.

    -          Please refer to the below example to create a custom exception. 

    package simplifiedjava.crackedInterview; 

    public class CustomException extends Exception { 

          private String message;     

          public CustomException(String message) {

                this.message = message;

          } 

          public String toString() {

                return message;

          }     

          public static void main(String[] args) {       

                try {

                        if(args.length >= -1) {

                            throw new CustomException("No Argument Exception");

                    }                

                }catch(CustomException e) {

                      System.out.println(e);

                }

          }

    }

    Output: No Argument Exception

     

     

    Click here to Purchase on AmazonClick here to Purchase on Amazon

    Click here to Purchase on Amazon

    Note: Please click on Image to Purchase the books from Amazon.in

        Can you identify which try, catch and finally block combination is valid?

    -          Following are the combinations.

    1.

    try {      

         

    }catch() {       

    }

    try {           

    }catch() {           

    } 

    2.

    try {           

    }catch() {           

    }

    try { 

    }finally {     

    } 

    3.

    try {           

    } 

    4.

    try {           

    }finally {           

    }catch() {           

    } 

    1 and 2 are valid.

    3 and 4 are invalid.

     

        Can we declare an empty catch block?

    -   Yes you can declare an empty catch block. But it's mandatory to declare any exception class in the catch block parameter.

    -    Please refer to the below example.

    package simplifiedjava.crackedInterview; 

    public class CustomException extends Exception {     

          public static void main(String[] args) {       

                try {                                         

                }catch(Exception e) {                 

                }

          }

    }

    It is mandatory to declare the Exception class name in the catch method signature.

    But inside the catch block, you can keep it blank. If you missed to declared an Exception in the catch method signature then you will get a compile-time error.

     

     

        Can you explain why NullPointerException occurred and how to handle it?

    -   Calling a method on null reference or trying to access a field of a null reference will trigger a NullPointerException.

    -    You can fix it either by making sure you are invoking the method non-null object.

    -   Make sure before invoking the method or modifying the field object is non-null.

    -          You can put a null check before invoking or performing any operation.

    -          You may use a try-catch block to handle NullPointerException.

    -          Please refer to the below scenario.

    a.       Trying to find the length of an array when it is null.

    b.      Calling the instance method on the null object.

    c.       Trying to modify the field of the null object.

    d.      Trying to count a length of String object when it is null.

    Demo 1: Put null check before invoking or performing any operation. 

    package simplifiedjava.crackedInterview; 

    public class NullPointerExceptionDemo { 

          String str;     

          public static void main(String[] args) {

                new NullPointerExceptionDemo().calculateLength();

          }     

          public void calculateLength() {

                if(str != null) {

                      System.out.println(str.length());

                }else {

                      System.out.println(" Variable is "+ str);

                }          

          }    

    }

    Output: Variable is null

     

    Demo 2: Put code inside try catch block. 

    package simplifiedjava.crackedInterview; 

    public class NullPointerExceptionDemo { 

          String str;     

          public static void main(String[] args) {

                new NullPointerExceptionDemo().calculateLength();

          }     

          public void calculateLength() {

                try {

                      str.length();

                }catch(NullPointerException e) {

                      System.out.println("Null Pointer Exception Handled");

                }                      

          }    

    }

    Output: Null Pointer Exception Handled

     

        Can you explain why ClassCastException occurred and how to handle it?

    - When you are trying to cast incompatible objects it triggers ClassClassException.

    - You can say ClassCastException occurs when you are improperly converting a class from one type to another type.

    -   When you are trying to convert a Human object into an Animal object which is incompatible.

    -     You can use instanceof operator to avoid ClassCastException.

    -     Please refer to below example to handle ClassCastException.

    package simplifiedjava.crackedInterview; 

    import java.util.ArrayList;

    import java.util.List; 

    public class ClassCastExceptionHandleDemo { 

          public static void main(String[] args) {

                List objList = new ArrayList();          

                objList.add(new Integer(10));

                objList.add(new Integer(10));

                objList.add(new Double(10.00));

                objList.add(new String("abc")); 

                for(Object obj: objList) {

                      if(obj instanceof Integer) {

                            System.out.println("Integer Type");

                      }else if(obj instanceof Double) {

                            System.out.println("Double Type");

                      }else if(obj instanceof String) {

                            System.out.println("String Type");

                      }                

                }          

          }

    }

    Output:

    Integer Type

    Integer Type

    Double Type

    String Type

     

        Can you explain why OutOfMemoryError occurred and how to handle it?

    -   OutofMemoryError occurs when your program is expecting more memory than JVM has available.

    -   OutOfMemoryError normally occurs when you have a code with an infinite loop.

    -    You can handle OutOfMemoryError by avoiding infinite loop.

    -  Allocate more heap space to JVM. Perm-Gen Space must increase but recently it has changed to meta-space.

     

        Can you explain why StackOverFlowError occurred and how to handle it?

    -      StackOverFlowError occurs when the nesting function calls too deeply.

    -   Generally StackOverFlowError comes in recursion functions. Recursion means a function calls itself.

    -    To avoid StackOverFlowError you have to make sure recursive call must terminate somewhere.

    -      Please refer to the below example for StackOverFlowerror.

    package simplifiedjava.crackedInterview; 

    public class StackOverflowErrorDemo { 

          public static void main(String[] args) {

                recursiveFunction(1);

          }    

          public static void recursiveFunction(int no) {

              System.out.println("Number: " + no);

              if (no == 0)

                return;

              else

                recursiveFunction(++no);

            }  

    }

    Output: Exception in thread "main" java.lang.StackOverflowError


        Can you explain why NoClassDefFoundError occurred?

    -    Java Virtual Machine is not able to find a particular class at runtime which was available at compile which triggers NoClassDefFoundError.

    -  If a class was present during compile time but not available in java classpath during runtime.

     

        Can you explain why ExceptionInInitializerError occurred?

    -   Whenever there is an error in the static block ExceptionInInitializerError will be thrown.

    -  Generally, this exception will be thrown at the time of class loading because static block executes at class loading time.

    package simplifiedjava.crackedInterview; 

    public class ExceptionInInitializerErrorDemo {

          static {

                      try {

                                  int no = 10/0;

                      }catch(NullPointerException e) {

                            e.printStackTrace();

                      }    

          }         

          public static void main(String[] args) {

                System.out.println("Main");

          }

    }

    Output: Exception in thread "main" java.lang.ExceptionInInitializerError

    Caused by: java.lang.ArithmeticException: / by zero    at simplifiedjava.crackedInterview.ExceptionInInitializerErrorDemo.<clinit>(ExceptionInInitializerErrorDemo.java:6)

     

        What's the difference between StackOverflowError and OutOfMemoryError in java?

    -          StackOverflowError: If there is no memory available in the stack for storing function call or local variable, JVM will throw StackOverflowError.

    -          OutOfMemoryError: If there is no memory available on heap memory while creating an object then JVM will throw OutOfMemoryError.


    • Java interview questions and answers all MNC - Click here
    • Basic core java interview questions and answers for freshers - Click here
    • Core java interview questions for 3 years experience - Click here
    • Core java interview questions and answers for 3-5 years exp - Click here
    • Core java interview questions and Answers for 5 - 7 Years exp - Click here
    • Basic Java Interview Questions and Answers - Click here
    • Java interview questions and answers on oops - Click here
    • Java interview questions and answers on Strings - Click here
    • Java interview questions on exception handling - Click here
    • Interview questions on multithreading in java for experienced - Click here
    • Interview questions on serialization in java for experienced - Click here

    • Interview questions on inner class in java for experienced - Click here
    • Interview questions on Collections in java for experienced - Click here


    Upcoming questions in next post:

    21. What is the difference between ClassNotFoundException and NoClassDefFoundError. 

    22. Can we skip finally block to execute. if yes then how.

    23. Can we have multiple catch blocks.

    24. how should be the sequence of List of Exception classes in catch block.

    25. what is the difference between final, finally and finalize.

    26. Can we create a try block inside a try block.

    27. Can we write try catch block inside a catch block.

    28. What are the rules we must follow while throwing exception in ovverridden method. 

    29. What is unreachable catch block error.

    30.Does finally block get executed if try or catch block has return statement. how the control flows in this situation.

    31. What is re-throwing exception in java.

    32. What is the difference between NoSuchMethodError and NoSuchMethodException.

    33. What is autoclosable resource.



    Previous Post                                                                    Next Post



    Thank you techies for visiting this blog. I hope you enjoyed this blog and got more technical knowledge. I have tried to cover all types of questions and provided examples tested on eclipse as much as I can. Guys, please don’t just mug up the questions and answers. Try to clear your concepts with examples. Try to write a code on eclipse once you read the concepts. It will help you to memorize the concepts for a very long time. Simultaneously you will be prepared for interview programs as well. It will help you to survive in the IT sector for a long time. It may be easy to crack an interview but it's really tough to survive in the IT industry with inadequate knowledge and skills. 

    I have collected all the questions from actual interviews attended by my friends, colleagues, college mate and classmate. I have covered frequently asked questions as well as challenging questions. I have included many programs to understand the concept thoroughly. I will try to explain the concept with the help of a real-time program in eclipse. 

    You can share more questions which are not covered in this blog or post. Always welcome your suggestions and queries. I will definitely try to resolve it. 

    Please comment your queries and new set of questions under the comment sections. I will create a new post for those questions. 

    My total experience is 10. Initially I had worked on some support projects and then I moved to java projects. I had worked with many multi-national companies like R-Systems, Tata Consultancy Services, Cybage Softwares.  Fortunately, TCS and Cybage has given me an opportunity to take interviews for experienced candidates. I have conducted more than 1000 interviews by now.

    Mock sessions will be conducted for minimal charges. I will guide you personally on how to crack interviews. All sessions will be online sessions only. My interview book will be provided free of cost if you enroll for personal training. Once you have done practice then I assured you will definitely crack almost all java interviews. 

    I have published my book named with "All MNC Java Interview" which is available on amazon. You can go through it or you can directly contact to me if you are interested to read the book. I will give you special discount. I have covered near about 550 questions and answers with program tested on eclipse and necessary diagram. 

    I have covered interview questions asked in all reputed MNC like TCS, Infosys, Capgemini, Tech Mahindra, Cognizant, City Bank, Barclays, Amdocs, Mindtree etc. My purpose behind this book is, help you to get a job in your dream company. I can understand this is a struggling period for job seekers and freshers. Everybody must have gone from this phase. so never give up. Keep upgrading yourself. I am sure you will get a job in your dream company. All the best!!! 

    Please reach out to me for personal training for interview preparation. 

    You can reach out to me at mncjavainterview@gmail.com.

     


    Post a Comment

    0 Comments