Sunday, August 26, 2012

Java Exception Handling Programming Questions


Q) What are the two types of Exceptions?
A)Checked Exceptions and Unchecked Exceptions.

Q) What is the base class of all exceptions?
A) java.lang.Throwable

Q)If the overridden method in super class A throws FileNotFoundException, then the overriding method present in class B which is a subclass of class A can throw IOException. If the above statement true?
A) The overriding method can not throw any checked exception other than the exception classes or sub-classes of those classes which are thrown by the overridden method.
In the scenario described in question, the method in class B can not throw IOException but can throw FileNotFoundException exception.

Q)Can we have a try block without a catch block?
public class JExample {

public static void main(String args[]){
int i=0;
int j=4;

try
{
int k=j/i;
}
finally{
System.out.println("finally");
}
}
}

Output:
=======
finally
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.test.JExample.main(JExample.java:11)

Q) What is the difference between checked and unchecked exception handling in Java? What are the disadvantages of checked exception handling?
A) 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.

Q)Explain try,catch and finally statements in Java ?
The try/catch statement encloses some code and is used to handle errors and exceptions that might occur in that code.

try {
   
} catch (Exception e) {
   
}finally{

}

Example
======

public class JExample {

public static void main(String args[]){
int i=0;
int j=4;

try
{
int k=j/i;
}catch(Exception e)
{
System.out.println("Exception caught");
e.printStackTrace();
}
finally{
System.out.println("finally");
}
}
}

Output:
======
Exception caught
java.lang.ArithmeticException: / by zero
at com.test.JExample.main(JExample.java:11)
finally


Q) If there is common code to be executed  in the catch block of 10 exceptions which are thrown from a single try block, then how that common code can be written with minimum effort?
A) In pre JDK 7, a method can be written and all catch blocks can invoke this method containing the common code.
In JDK 7, the | operator can be used in catch block in order to execute common code for multiple exceptions. e.g. catch(SQLException sqle | IOException ioe){}
4) Have you every created custom exceptions? Explain the scenario?
Ans: Custom exceptions are useful when the JDK exception classes don’t capture the essence of erroneous situation which has come up in the application. A custom exception can be created by extending any subclass of Exception class or by implementing Throwable interface.

Q) What is the difference between Validation, Exception and Error?
A)Validation is the process of making user enter data in a format which the application can handle.
Exception handling is the process when the application logic didn’t work as expected by the Java compiler.
Error occurs in a situation where the normal application execution can not continue. For e.g. out of memory.

Q) What is the purpose of finally block? In which scenario, the code in finally block will not be executed?
A) finally block is used to execute code which should be executed irrespective of whether an exception occurs or not. The kind of code written in a finally block consists of clean up code such as closing of database/file connection.
But JDK 7 has come up with try with resources block which automatically handles the closing of resources.

Q) Can a finally block exist with a try block but without a catch?
A)Yes. The following are the combinations try/catch or try/catch/finally or try/finally.

Q) What is the difference between throw and throws?
Throw is used to explicitly raise a exception within the program, the statement would be throw new Exception(); throws clause is used to indicate the exceptions that are not handled by the method. It must specify this behavior so the callers of the method can guard against the exceptions.
Throws is specified in the method signature. If multiple exceptions are not handled, then they are separated by a comma. the statement would be as follows: public void doSomething() throws IOException,MyException{}

Q) How to create Custom Exception in Java?
package com.test;

//NullException is the user exception defined
class NullException extends Exception{

int a;

public NullException(int i) {
i=a;
}

public String toString(){
return "Created NullException:"+a;
}
}
public class CustomException
{

public static void Divide(int a,int b) throws NullException{

int k=a/b;
throw new NullException(k);
}
public static void main(String args[]){

try{

CustomException c=new CustomException();
c.Divide(5, 2);
}catch(Exception e){
System.out.println("Main CustomExceptionm:" +e);
}finally{
System.out.println("Finally Exceuting");
}

}
}

Output
=========
Main CustomExceptionm:Created NullException:0
Finally Exceuting

Q) What are the differences between NoClassDefFoundError and ClassNotFoundException?
A) 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.


Q) Can a catch block exist without a try block?
A)No. A catch block should always go with a try block.

Q) What will happen to the Exception object after exception handling?
A)Exception object will be garbage collected.

Q)How does finally block differ from finalize() metho
Finally block will be executed whether or not an exception is thrown. So it is used to free resoources. finalize() is a protected method in the Object class which is called by the JVM just before an object is garbage collected.

Q) What is the purpose of throw keyword? What happens if we write “throw null;” statement in a Java program?
A) ”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.


Q) return statement in try,catch and finally ?
public class ExceptionDemo {

public int chkException(int arr[]){

int k=0;
int t=1,c=2,f=3;
try
{
for(k=0;k<5;k++)
System.out.println("arr Element"+arr[k]);
System.out.println("Try Catch");
return t;
}catch(Exception e){
System.out.println("Failed on exception"+e.getMessage());
System.out.println("Catch Retrun");
return c;
}finally{
System.out.println("Finally Return");
return f;
}
}

public static void main(String args[]){

int arr[]={1,4,5};

ExceptionDemo e=new ExceptionDemo();
e.chkException(arr);

}
}

Output
============
arr Element1
arr Element4
arr Element5
Failed on exception3
Catch Retrun
Finally Return

2 comments:

Thanks for your valuable comments