Friday, October 14, 2016

Java Exceptions Interview Questions and Answers

Hii !! Today we will learn Exception handling interview questions in java. These Interview questions frequently asked in technical Round. Before face the technical round just brush up and get clear the round. In real time project while you are developing the code you may face lot of  exceptions and errors and  I  had already written article Top10 exceptions in java. Interviewer maximum time used to spend in this area since he want test to you how much knowledge you have when there is issue will raised in your code then how soon you can debugging your bugs. So, lets start some of the frequently exception handling interview questions.

1. What is Exception in Java?

Ans:  Exception is an Error event that can happen during the execution of the program and abrupt it's normal flow. These exception may raise from different kind of situation such as wrong data entered by user,hardware failure,network connection failure etc..

                Java Exception Handling framework is used to handle the runtime errors only,compile time errors are not handled by exception handling framework.

2. What are  the Exception Handling keywords in java?

Ans:  There are four keywords used in java exception handling:

 a) 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 the try block to handle the exceptions. we can have multiple catch blocks with a try and try-catch block can be nested also.

b) throw: 

Sometimes we explicitly  want to create exception object and then throw  it to halt the normal processing of the program, throw keyword is used to throw exception to the reuntime to handle it.

c) throws:

when we are throwing any checked 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. We can provide multiple exceptions in the throws clause and it can be used with main() method also.

d) 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 always gets executed ,whether exception occurs or not.


3. Difference between Checked and Unchecked Exception in Java?

Ans:  

  • Checked Exception is required to be handled by compile time  while unchecked exception doesn't.
  • Checked Exception is direct sub-class of exception while unchecked Exception are of Runtime Exception
  • Checked Exception represents scenario with higher failure rate while unchecked Exception are mostly programming mistakes.



4. Example of Checked Exception in java?

Ans:  Fallowing are some example of checked exception in java

  • IOException
  • SQLException
  • DataAccessException
  • ClassNotFoundException
  • InvocationTragetException
5. Example of UnChecked Exception in java?

Ans:  Fallowing are few examples of UnChecked Exception in java

  • NullPointerException
  • ArrayIndexOutOfBound
  • ArithmethicException
  • IllegalStateException
6. Tell me How to Use Multiple catch block in Java 7?

Ans:

      If you are catching a lot of exceptions  in single try block, you will notice that catch block code looks very ugly and mostly consists of redundant code to log the error, Keeping this in mind Java 7 one of the feature was multi-catch block where we can catch multiple exceptions in a single catch block. This catch block with this feature looks like below:

Example:
 catch(IOException|SQLException| Exception ex)
{
logger.error(ex);
throw new MyExeption(ex.getMessage());
}

Most of the time, we use finally block just to close the resources and sometime we forget to close them and get runtime exceptions when the resources are exhausted. These excecption are hard to debug and we might need to look into each place where we are using that type of resource to make sure we are closing it. So java 7 one of the improvement was try-with-resources where we can create a resource in the try statement itself and use it inside the try-catch block,runtime environment automatically close these resources.  Sample of try-catch block with  improvement is:

Example:

try(MyResource mr=new MyResource())
{
System.out.println("MyResource created in try-with-resources");
}
catch(Exception e)
{
e.printStackTrace();
}

7. Difference between throw and throws Keyword in java?

Ans:

  • throw is used to explicitly throw and exception. throws is used to declare an exception
  • checked exception can not be propagated with throw only.checked exceptions can be propagated with throws.
  • throw is used within the method. throws is used with the method signature.
  • you can not throw multiple exceptions,you can declare multiple excpetions
            Ex: public void method() throws IOException,SQLException

8. How to write Custom Exception in java?

Ans:  We can extend Exception class or any of it's subclasses to create our custom or user defined exception class. The custom exception class can have it's  own variables and methods that we can use to pass error codes or other exception related information to the exception handler.
   
    More about Custom Exception click here: User defined Exception in java

9. What is OutOfMemoryError in java?

Ans: OutOfMemoryError in java is a subclass of java.lang.VirtualMachineError and it's thrown by JVM when it ran out of heap memory. We can fix this error by providing more memory to run java application through java.

Ex:  $>java MyProgram-
           Xms1024m-Xmx1024m-
           XX:PremSize=64M-
           XX:MaxPermSize=256m


10. What happens when exception is thrown by main() method?

Ans: When exception is thrown by main() method, java Runtime terminates the program and print the exception message and stack trace in system console.

11. Can we have empty catch block?

Ans:  we can have an empty catch block but it's the example of worst programming. We should  never have empty catch block because if the exception is caught by that block,we will have no information about the exception and it will be a nightmare to debug it. There should be at least a logging statement to log the exception details in console or log files.

12. Is there any case when finally will not be executed?

Ans: finally block will not be executed if program exists( either by calling System.exit() or by causing a fatal error that causes the process to abort)

           
13. What is NullPointerException?

Ans: NullPointerException is thrown when calling the instance method of a null object,accessing or modifying the filed of null object etc..

14) When is the ArrayStoreException thrown?

Ans: When copying elements between different arrays,if the source or destination arguments are not arrays or their types are not compatible,then ArrayStoreException will be thrown.

15) What are difference between error and exception?

Ans: An error is an irrecoverable condition occurring at run time such as OutOfMemory error Whereas Exceptions are conditions that occur because of bad input etc..Example: FileNotFoundException will be thrown if the specified file does not exist.

16) Is it necessary that each try block must be followed by a catch block?

Ans: It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block or a finally block.  

17) When throws keyword is used?

Ans: If a method does not handle a checked exception,the method declare it using the throws keyword. The throws keyword appears at the end of a method's signature.

18)  How finally used under Exception Handling?

Ans: The finally keyword is used to create a block of code that follows a try block. A finally block of code always executes,whether or not an exception has occurred. 

19) What things you should follow while creating your own exceptions in Java?

Ans: The following points should be kept in mind while creating your own exceptions:

  • All exceptions must be a child of Throwable
  • If you want to write a checked exception that is automatically enforced by the handle or Declare Rule. You need to extend the Exception class
  • You want to write a runtime exception,you need to extend the RuntimeException class
20)  When ArithmeticException is thrown?
 
Ans: The ArithmeticException is thrown when integer is divided by zero or taking the remainder of a number by zero. It is never thrown in floating-point operations.
 
21)What is difference between ClassNotFoundException and no class defined error?
 
Ans
 
ClassNotFoundException: Thrown when an application tries to load in a class through its string name using:
  1. The forName() method in class Class
  2. The findSystemClass() method in class ClassLoader
  3. The loadClass() method in class ClassLoader
But no defination for the class with the specified name could be found.
 
NoClassDefFoundError:
 
  1. Thrown if the java Virtual Machine or a ClassLoader instance tries to load in the definition of a class and no defination of the class could be found
  2. The searched-for class definition existed when the currently executing class was compiled,but the definition can no longer be found.
 Recommended to Read:
 
     

 




   

2 comments:

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...