Exception Handling


                                                    Exception Handling

Q. What is an Exception?
A. Exception are the Objects representing the logical errors or run time errors or abnormal situations.
Any Object which has been generated for representing a runtime error can be called as Exception.

Exception class Hierarchy:

Kinds of Exception:
Checked Exception: Exception and its direct sub classes are called checked exception (except RuntimeException) because if we raised these exception using "throw" keyword.
   We must catch or should report these exception else compiler throws exception.  "CE: unreported exception must be caught or declared to be thrown".
 
Unchecked Exception: RuntimeException sub classes and error classes are called unchecked exception.

Runtime Exception: RuntimeException sub classes are called run time exception because they are raised due to the problem in operator exception.

Error: Error and its sub classes are called Errors.

Q. What is an Exception handling?
A. The process of identifying an exception and catching them and assigning that exception to the reference of the corresponding Exception class is known as Exception Handling.

Q. What the use of Exception Handling?
A. 1) To stop abnormal termination.
   2) To provide user understandable messages when exception is raised.
 
Q. How to Handle exception?
A. Procedure to handle the Exception:
1. Prepare the Exception Object appropriate to the current logical mistakes.
2. Throwing that exception to the appropriate exception handler.
3. Catching that exception.
4. Taking necessary actions against that exception.

Q. How can Handle Exception in Java.
A. SUN has given two keywords/ blocks try and catch.

try: try keyword establishes a block to write a code that causes exception and its related statements.
     Exception causing statements must be placed in try block to handle and catch exception for stopping abnormal termination and to display end user understandable message.

catch: catch block is used to catch exception those are thrown from its corresponding try block. It has logic to take necessary actions on that caught exception.
catch block syntax is looks like constructor syntax. It does not take accessibility modifier , return type. It takes only single parameter of type Throwable or its sub classes.

Syntax: try{
//Logic that may occurs exception
}
catch (Exception e) {
   // User understandable message
}

Q. What is finally block? what is the need of finally block?
A. Finally: finally establishes  block that definitely executes statements placed in it. Statements which are placed in finally are always executed irrespective of the way the control
is coming out from try block either by completing normal or by returning statement or by throwing exception.
Need of finally: Resource releasing code placed inside finally block.

Note:
1. Throwable is the super class of all Exception classes.
2. JVM always executes try block statements.
3. catch block statements are executed only if its parameter type exception is raised in its corresponding try block.
3. When an exception is raised in the try block JVM creates that exception type class object and check for match in among all catch blocks. If match is found JVM executes that catch block 
   and also statement written after all catch blocks finally it terminates program execution normally.
4. catch block parameter must be of type java.lang.Throwable or its sub classes else it leads to "CE: Incompatible Type".
5. If we return a value in try block and if we do not return value at end of method then it leads to "CE: missing return statement".

Q. What is throws and throw keywords in Java.
A. throws: throws is used report that raised exception to the caller. It is mandatory for checked exception for reporting if they are not handled.
 -> throws keyword must follow Throwable type of class name.
 -> It must be used in method prototype after parenthesis.
 
 Syntax: void m1() throws IOException {}

 throw: throw keyword is used to throw exception the manually. In most of the cases we use it for throwing checked exception explicitly.
-> throws keyword must follow Throwable type of object.
-> It must used only in side method logic.

 Syntax: void m1() {
throw new ArithemeticException
}
Note: we are not allowed to write catch with checked without throwing it from the try block else it leads to exception.
  "CE: exception never thrown from the corresponding try statement".

Special case: We are allowed to place catch for Exception and Throwable even though they are not thrown from try block because they are super classes of both checked and unchecked.
  But of they are thrown using keyword they must be handled or reported else it leads to exception:
  "CE: unreported exception java.lang.Exception must be caught or declared to be thrown".
 Case 1: If super class method is not reporting or not throwing checked exception sub class overriding method is not allowed to throw checked exception.
 Case 2: If super class method has throws clause sub class overriding method may or may not have throws clause. If we place the throws clause in overriding method it must be either
same Exception class or sub class. It should not be super or sibling also we can not add more exception to throws clause.


Q. What is Exception Propagation?
A. The process of sending from called method to calling method is called exception propagation. If an exception is propagated not only method execution but also calling method
   execution is terminated abnormally if exception is not caught in calling method in the main method.

Example:

class Example{
void m1(){
try{
System.out.println("Start M1");
System.out.println(10/0);
System.out.println("End M1");
  } catch (ArithemeticException ae){
System.out.println("Catch M1");
  }
}
public static void main (String[] args){
System.out.println("Start main");
m1();
System.out.println("End main");
}
}
 
   Rule 1: If exception is caught in m1() method then exception is not propagated to calling method.
   
   Rule 2: If the exception is not caught in m1() method then it is propagated to calling method.
   class Example{
void m1(){
    System.out.println("Start M1");
System.out.println(10/0);
System.out.println("End M1");
}
public static void main (String[] args){
System.out.println("Start main");
m1();
System.out.println("End main");
}
}

Rule 3: To have smooth execution in calling method propagated execution should be caught with try/catch.

class Example{
void m1(){
System.out.println("Start M1");
System.out.println(10/0);
System.out.println("End M1");
}
public static void main (String[] args){
System.out.println("Start main");
try{
m1();
} catch (ArithemeticException ae){
System.out.println("In catch");
}
System.out.println("End main");
}
}

Q. What is User Defined Exception?
A. User Defined Exception or custom exception is creating your own exception class and throws that exception using throw keyword.
This can be done by extending the class Exception.
 Example:

 class MyException extends Exception{
   String str;
   MyException(String str1) {
str=str1;
   }
   public String toString(){
return ("User Defined Exception Occurred: "+str) ;
   }
 }


class ExceptionTest{
   public static void main(String args[]){
try{
System.out.println("Start try block execution");
throw new MyException("This is User Defined Message");
} catch(MyException exp){
System.out.println("Start catch block execution") ;
System.out.println(exp) ;
}
   }
}

Note: -> Extend the Exception class to create your own exception class.
  -> You don't have to implement anything inside it, no methods are required.
          -> You can have a Constructor if you want.
          -> You can override the toString() function, to display customized message.

Q. What is similarity between NullPointerExceeption and ArrayIndexOutOfBoundException.
A. Both are unchecked Exception and derived from RuntimeException.

Q. Explain about ClassNotFoundException and NoClassDefFoundException.
A. ClassNotFoundException: ClassNotFoundException occurs when class loader could not find the required class in sub classpath, so basically you should check your classpath and
   added the class in the classpath.
   It thrown when an application tries to load a class through its name but no definition for the class with the specified name could be found.

   NoClassDefFoundException: This is more difficult to debug and find the reason. This is thrown when at compile time the required classes are present but at the run time the
classes are changed or removed or class static initializer throw exception. It means the class which is getting loaded is present in classpath but one of
the classes which are required by this class are either removed or failed to load by compiler.
It thrown if JVM tries to load in the definition of a class and no definition of the class could be found.


Q. What is the difference between Checked and unchecked exception.
A. Checked Unchecked
   1. All those Exception which required being 1. All those Exception whose handling is not
     catches and handled during compile time    verified during compile time.
otherwise compiler throw the exception.

   2. Checked exception is direct sub class of 2. Unchecked exception is direct sub classes of
      Exception.    RuntimeException and Error.

3. Checked exception is required to be 3. Unchecked Exception doesn't.
handled by compiler.

4. checked exception represent scenario 4. Unchecked exception are mostly programming
   with higher failure rate.    mistakes.

 
Q. What is the difference between Exception and Error.
A. Exception Error
   1. We can catch and handle the Exception.   1. We can't catch Error so can't handle it.

   2. We can catch Exception type exception 2. We can't catch Error type exception, because
     because JVM process will not be terminated.       if error type exception is raised then JVM
   process will be terminated.
 
Q. What is the difference between throw and throws.
A. throw throws
   1. throw keyword is used to throw exception 1. throws keyword is used in method declaration
  from key method or static block in Java.         denoted which Exception can possible be thrown
   by this method.

2. throw keyword can be used in switch case 2. throws keyword can't be used anywhere except on
in Java.    method declaration.

3. throw transfer control to caller. 3. throws is suggest for information and compiler
checking.


Comments