Sunday, October 24, 2010

Exception in Java

point 1 : For each and every logical error there is a corresponding exception class  in
 java.lang.package.


Question : How Exception Handling Works ?
Ans : Whenever a logical error occurs, the JVM creates corresponding object for that Exception class, and these objects are not explicitly handled, these objects will 
reach back to JVM. JVM accepts these objects and terminates the Program.


Question : What is JVM?
Ans : Java Virtual Machine is a set of Programs.


Question : Define Exception Handling ?
Definition 1 : Concept of Handling the exception class objects by avoiding them to reach 
back to JVM is called to Exception Handling.


Definition 2 :  Exception Handling is a mechanism for handling the exceptions by 
detecting and responding to exceptions in a uniform and reliable manner.


Question : What is the Difference between the throw and throws ?
Answer:
Throws: is used to mention or indicate that to the compiler as well as the end user, 
that a particular function is proven to generate exception class object and those 
 objects are not handled in the function itself.


In Simple Words, we can use the throws clause on the method instead of try and catch
Exception handler.


Throw: is used to explictly transfer the use defined exception class object
 from the function to the calling place.


 The throw keyword (note the singular form) is used to force an exception. 
 Moreover throw keyword can also be used to pass a custom message to the 
  exception handling module.


Question : How to Handle these Exception class objects?
Ans : By assigning them to corresponding exception class.


Question: What are simple logical Errors and Serious logical errors?
Simple logical Errors : can be neglected by the JVM.
Example : Divided by Zero.
Serious logical Errors: cannot be neglected by the JVM.
Example: Out of Heap Memory.


Note: Throwable Class is the super class of Exception and Error Classes.
Note: All classes under Error class are Serious logical errors.
All classes under the Exception class are simple logical errors.


Question: Why cant we write the catch statement like this catch(Throwable t)?
Ans: Throwable class is super class of Error class,and by using the above statement
 we are indirectly handling the Error class Objects,which is not Possible. 
Because  we are not allowed  to handle Serious logical errors.


Question: what is Checked Exception ?
Ans : The Exception Objects for which the compiler compels to handle them are knowns
as checked Exception.
Other Definition : The Exceptions which are checked by the compiler for smooth
execution of program at run time is called Checked Exception.


Example : ClassNotFoundException , IOException,  FilenotFoundException
SQLException.


Question : What is unchecked Exception?
Ans: The Exception Objects for which the compiler does not compels to handle them 
are  known as Un-checked Exception.
Other Definition : The Exceptions which are unable to check by the compiler are 
called UnChecked Exceptions.


Example: ArrayIndexOutOfBound, Divided by Zero. IllegalStateException.
ClassCastException.Arithmetic Exception.


Observation 1: unchecked Exception must extend the Run time Exception class (or)
    Arithmetic Exception (or) Null Pointer Exception Class.
Observation 2: Exception which extends the RunTime Exception class are called 
  unChecked Exception.


Checked Exception :
Observation 1  : Checked exception does not extends the runtimeException class.
Observation 2  : Used to avoid the compile time errors.  


Note: If a method throws an exception then it is may or may not be mandatory to
 call that function from the try and catch Block.


Question: What is the calling function of main method?
Ans : JVM.


Note: If an Exception object reaches the JVM, then program will terminates.


Question : If a Code written outside of the finally block , will that code get executed?
Answer :   try{
                        System.out.println("sekhar");
                 }catch(Exception e ){
                      e.printStackTrace();
               }finally{
                     System.out.println(" i am in Finally Block");
              } System.out.println(" I am Out of the Finally Block");


O/p: :
                    sekhar
                    i am in Finally Block
                    i am out of finally block


Observation : After the finally block the code will execute as usual.


Question : I have written an throw statement and followed by the finally block and
                   a set of statements, will that statements get executed?


Consider this example :
  public static int divideByZero(int first,int second) throws MyException{
try{
if(second == 0){
   throw new MyException("can't divided by Zero ");     
}else{
   System.out.println(" in Else ");
   return first/second;
}finally {     
   System.out.println(" i am in Finally Class");
}
System.out.println(" I am Not Reachable ");


Observation : Finally block will get executed irrespective of the throw statement,
             and after finally block no code is going to execute.


Question : Observe the below code :

public static int divideByZero(int first,int second) throws MyException{
try{
if(second == 0){
   throw new MyException("can't divided by Zero ");     
}else{
   System.out.println(" in Else ");
   return first/second;
}
}catch(Exception e){
   System.out.println("  i am in Exception Class");
}finally {    
   System.out.println(" i am in Finally Class");
}
System.out.println(" I am Out of Finally ");
return 8;
    }


Here the output is :

U Throwed the Exception :can't divided by Zero 
  i am in Exception Class
 i am in Finally Class
 I am Out of Finally 
 Value : 8
Observation :
once we thrown-ed the exception we are catching it in exception block, so the once after
exception is caught, that exception will dead. so here followed by finally block execution
and followed by normal execution of the code.


Observation 1 : Even- though you return a value, the finally block will still get Executed.


Observation 2: throw new MyException("can't divided by Zero ");
                 System.out.println(" Vizag ");
                return 50;


Any Statements written after the throw command those are just unreachable.

Question : Write an Example for the user defined Exception ?
Answer :    public class MyException extends Exception{
    
    public MyException(String exp){

System.out.println(" U Throwed the Exception :"+exp);
    }    
}


------------------This class throws the actual  exception object of above class-----------

public class ThrowException {


    public static int divideByZero(int first,int second) throws MyException{

if(second == 0){
   throw new MyException("can't divided by Zero ");
}else{
   return first/second;
}
    }
    public static void main(String[] args) {  
   try {
int value = divideByZero(4,0);
   } catch (MyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
   }
    }
}
------------------------------------------------------------------------
O/p : MyException
at ThrowException.divideByZero(ThrowException.java:12)
at ThrowException.main(ThrowException.java:21)
      U Throwed the Exception :can't divided by Zero.

Observation : A user defined exception class must extends the Exception class.

Question : How will you define an Exception in Java?
Answer 1:  An Exception is an event which occurs during the execution of a program,
that will disrupt the normal flow of the program instructions.
Answer 2 : Exceptions are objects that define the abnormal condition that 
interrupts the normal flow of Execution.

Detailed Exception Hierarchy :
Question : Explain the exception Hierarchy of Exception Handling?
                                 Throwable 
          |----------------------- | ------------------------------------------------|
        Exception                                                                           Error
 | ------------------------------------|                             | ---------------------|
 Interrupted Exception  RunTime                   Thread-Death   Linkage Error.
                         |----------------- | -----------------|
                           Arithmetic     Null Pointer     ClassCast Exception.  



Q)  What will happen to the Exception object after exception handling?
Rep) It will go for Garbage Collector. And frees the memory.



Question : What are the cases of ClassCastException ?
Ans :  u Created a collection suppose TreeSet, and you added some interge values for that
collection.And if you try to insert string Objects into that collection, at run time it throws
it throws ClassCastException Exception.
Example :

package Collection;
import java.util.Set;
import java.util.TreeSet;
public class ClassCast {
public static void main(String[] args) {
Set mySet = new TreeSet();
mySet.add(new Integer(40));
mySet.add(new Integer(50));
mySet.add(new Integer(60));
mySet.add(new Integer(70));
mySet.add(new Integer(80));
mySet.add(new String("my String"));
}
}


o/p :

Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
at java.lang.String.compareTo(Unknown Source)
at java.util.TreeMap.put(Unknown Source)
at java.util.TreeSet.add(Unknown Source)
at Collection.ClassCast.main(ClassCast.java:22)


Observe the BELOW code CAREFULLY :

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;




public class ExceptionQuestion {


/**
* @param args
*/
public static void main(String[] args) {


try{
BufferedReader bf = new BufferedReader(new FileReader("C:\\Movies\\MyFile.txt"));
throw new FileNotSupportedException();

}catch(FileNotFoundException fnf){
fnf.printStackTrace();
}catch(FileNotSupportedException ffns){
ffns.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}
}


}



public class FileNotSupportedException extends Exception {


/**
* @param args
*/
FileNotSupportedException(){


}
public static void main(String[] args) {

}
@Override
public String toString(){
return "FileNotSupportedException  Sekhar";

}


}
o?P:::: 
FileNotSupportedException  Sekhar
at ExceptionQuestion.main(ExceptionQuestion.java:17)









No comments:

AWS certification question

AWS AWS Hi! this is for questions related to AWS questions. EC2 instances EC2 storage types cold HDD : 1. Defines performance in terms...