Wednesday, April 13, 2011

Exception Handling Questions

Q) Diff Exception & Error
Exception & Error both are subclasses of the Throwable class.

Exception is generated by java runtime system (or) by manually. An exception is a abnormal condition that transfer program execution from a thrower to catcher.
Error will stop the program execution, Error is an abnormal system condition. We can handle the error by extending with our class with throwable. Actually jvm handles the Errors If you try to catch the errors then jvm will not catch them this may even result in the collapse of JVM.

Q) Try & Catch, Throw, Throws
Try & catch This is used to fix up the error, to prevent the program from automatically terminating, try-catch is used to catching an exception that are thrown by the java runtime system. The final concept is there should be a single try, multiple catch blocks and a single finally block in a try-catch- finally block.
Throw is used to throw an exception explicitly. (If an exception has occurred in a method, you may want to catch
it and re-throw it to the calling method. Sometimes, you might want to catch one exception but re-throw another 
one that has a different description of the error). The flow of execution stops immediately after the throw statement; any subsequent statements are not executed.
Throws If a method is capable of raising an exception that it does not handle, the method must specify that the exception have to be handled by the calling method. Throws clause list the type of exceptions that a methods might through.

Q) What happens if a try-catch-finally statement does not have a catch clause to handle an exception that is thrown within the body of the try statement?
exception propagates up to the next higher level try-catch statement  or results in the program's termination.

Q) Checked & UnChecked Exception :-
Checked Exception are those which the java compiler forces you to catch. eg, IOException thrown by java.io.FileInputStream's read() method·
            
Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time. eg, StringIndexOutOfBoundsException thrown by String's charAt() method· Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.

Checked Exc (Compile Time)
Un Checked Exc (Run Time)
ClassNotFound.Exc
Arithmetic. Exc
NoSuchMethod. Exc
IndexOutOfBound. Exc
ArrayIndexOutOfBound. Exc
StringIndexOutOfBounds
NoSuchField. Exc
ClasscastException
Interrupted. Exc
IllegalArgument. Exc
IllegalAccess.Eec
IllegalMonitorSate. Exc
CloneNotSupported. Exc
IllegalThreadState. Exc
FilenotFound. Exc
NullPointer. Exc

NumberFormat. Exc

ArrayIndexOutOfbound Accessing an array element by providing an index value <0> or equal to the array size.
Arithmetic Exception     such as divide by zero.
ClassNotfound Exception       class not found.
IllegalArgument Exception    Illegal argument is used to invoke a method.
NosuchField Exception          A request field does not exist.
NosuchMethod Exception      A request method does not exist.
Nullpointer Exception  Call a method on an object, but the object reference was null(object is not initialized).
NumberFormat Exception  Invalid conversation of string to numeric format.
OutOfMemoryError       Signals that JVM has run out of memory and that the garbage collector is unable to
                                                     claim any more free memory.
StackOverFlow           Signals that a stack O.F in the interpreter.
StringIndexOutOfbound  Accessing character of a string or string buffer with index values <0> or equal to the array size.
ArrayStore Exception Assignment to an array element of an incompatible type.
ClasscastException    Invalid casting.
Instantion Exception  Attempt to create an object of an Abstract class or Interface.

Q) Methods in Exceptions?
getMessage(), toString(), printStackTrace(), getLocalizedMessage(),

Q) Can an exception be rethrown?
Yes, an exception can be rethrown.

Q) Exception Chaining?
Is a list of all the exceptions generated in response to a single root exception. As each exception is caught and converted to a higher-level exception for rethrowing, it's added to the chain. This provides a complete record of how an exception is handled  Two methods and two constructors were added to Throwable.
Throwable getCause()
Throwable initCause(Throwable)
Throwable(String, Throwable)
Throwable(Throwable)

The Throwable argument to initCause and the Throwable constructors is the exception that caused the current exception. getCause returns the exception that caused the current exception, and initCause returns the current exception.

Q) Does it matter in what order catch statements for FileNotFoundException & IOExceptipon are written?
Yes, it does. The FileNoFoundException is inherited from the IOException. subclasses have to be caught first. (EOFException is a subclass of the IOException)

Q) How does a try statement determine which catch clause should be used to handle an exception?
When an exception is thrown, the catch block of the try statement are examined in the order in which they appear. The first catch block that is capable of handling the exception is executed. The remaining catch blocks are ignored.

Q) Is it necessary that each try block must be followed by a catch block?
It is not necessary, It should be followed by either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method.

Q) Creating User defined exceptions? Throw Exception example?
The user defined exception class should extend from Exception class. The toString() method should be overridden in the user defined exception class in order to display meaningful information about the exception.

class MyException extends Exception {
   public String getMessage() {
              return ("This is my exception....");
   }
}

public class UserDefinedExecepDemo {
public static void test() throws MyException {
                        String ss="AmitTest";
                                   
                        if(!ss.equals("amit"))
                         throw new MyException();
            }
                       
            public static void main(String args[]) throws MyException,IOException {
                  try {
                          test();
                        }catch(MyException e){
                                    System.err.println(e.getMessage());
                        }catch(Exception e){
                                    System.err.println(e);
                  }
} }