Monday, August 20, 2012

Thread Interview Questions in Java


1) What is the difference between checked and unchecked exception handling in Java? What are the disadvantages of checked exception handling?
Ans: Checked exceptions are the one for which there is a check by the compiler that these exceptions have to be caught or specified with throws keyword. These kind of exceptions occur because of conditions which are out of control of the application like Network error, File Access Denied etc.
Unchecked exceptions are the one which arise because of logic written by the developer. e.g. Trying to access an array element which doesn’t exist.

Multiple exceptions in single catch block
catch(FileNotFoundExcpetion fne | Exception e){}

What are the differences between NoClassDefFoundError and ClassNotFoundException?
Ans: NoClassDefFoundError occurs when a class was found during compilation but could not be located in the classpath while executing the program.
For example: class A invokes method from class B and both compile fine but before executing the program, an ANT script deleted B.class by mistake. Now on executing the program NoClassDefFoundError is thrown.
ClassNotFoundException occurs when a class is not found while dynamically loading a class using the class loaders.
For example: The database driver is not found when trying to load the driver using Class.forName() method.

What is the purpose of throw keyword? What happens if we write “throw null;” statement in a Java program?
Ans: ”throw” keyword is used to re-throw an exception which has been caught in a catch block. The syntax is “throw e;” where e is the reference to the exception being caught. The exception is re-thrown to the client.
This keyword is useful when some part of the exception is to be handled by the caller of the method in which throw keyword is used.
The use of “throw null;” statement causes NullPointerException to be thrown.
The answers are brief. Do post your comments if you think I have missed anything or discuss any other exception handling question.

No comments:

Post a Comment

Thanks for your valuable comments