Showing posts with label Exception Handling. Show all posts
Showing posts with label Exception Handling. Show all posts

Wednesday, February 11, 2009

Java DefaultExceptionHandler

An Exception is an abnormal and unexpected and also unwanted event that disturbs the normal flow of the program.
Ex: FileNotFoundExceptionArithmaticException etc..
Default Exception Handling Mechanism in JAVA:
class Sample
{
public static void main(String a[])
{
doStuff();
}
public static void doStuff()
{
doMoreStuff();
}
public static void doMoreStuff()
{
System.out.println(“hai”);
System.out.println(10/0);
}
}



RTE: Exception in thread “main” Java.Lang.Arithematic Exception: /by zero
At Sample . doMoreStuff(Sample.java)
At Sample . doStuff(Sample.java:9)
At sample . main(Sample. java :5)
• If an exception is raised inside any method is r3esponsible for the creation of exception object. (here doMoreStuff() is responsible )
• The Exception object must contain the fallowing information.
1. Name of the Exception(Java.Lang.ArithematicException)
2. Description of the Exception (/ by zero)
3. The position at which the exception raised. (stack trace).
• Now the method handover that exception object to the JVM. JVM will come with that exception object and it will check, is there any exception object and it will check is there any exception handler inside that method abnormally and removes the corresponding entry from the stack.
• Now the method handover that exception object to the JVM. JVM will come with that exception object and it will check, is that any exception handler inside that method. If there is no exception handler then JVM blindly terminate that method abnormally and removes the corresponding entry from the stack.
• JVM will check for the caller(doStuff()) containing any exception handling code. If the caller also doesn’t contain any exception handling code, then JVM simply terminate that method also and remove the corresponding entry from the stack.
• This process will continue, until main() method. If the main() also doesn’t have any exception handling code then JVM terminates main() abnormally and handover the responsibility of the exception handling to default exception handler.
• Now Default Exception handler print the exception information to the end user
CommonExceptions and Errors:
Exceptions or errors may be thrown by either JVM(JVM Exceptions) or thrown explicitly by application developers or API programmers(programmatic exception).
1. NULLPOINTER EXCEPTION:
Class Sample
{
Static int[] a;
Static String name;
public static void main(String a[])
{
System.out.println(a.length);
}
}
System.out.println(a[o]); // null pointer exception (NPE)
System.out.println(name.length); //NPE
This is child class of RuntimeException. It is unchecked exception.
This is thrown by JVM when attempting to acess an object with a reference variable whose current value is null.
Ie., on null if we are applying any operation we will get NullPointerException.
2. STACK OVERFLOW ERROR:-
• This is child class of virtual machine error.
• It is unchecked
Throwable ----> Error ---> VMError ---> StackOverFlowError
Ex:class Sample
{
public static void m1()
{
m1();
}
public static void main(String a[]){ m1(); } // stack overflow error
}
StackOverflow error is thrown by JVM when a method recurses too deeply.
class Sample
{
Sample() { new Sample(); }
public static void main(String a[]) { Sample s= new Sample(); }//Exception in main thread stack overflow error
}
3. ARRAY INDEXOUTOF BOUNDS EXCEPTION:
• This is a child class of IndexOutOfBoundsExcption.
Throwable ---> Exception ---> RunTimeException ----> IndexOutOfBoundsException---> ArrayIndexOutOfBoundsException, StingIndexOutOfBoundsException
• It is an unchecked exception thrown by JVM when we are accessing an array element with
Invalid index.
Ex:
class Sample
{
public static void main(String a[])
{
Int[] a=new int[6];
System.out.println(a[5]); //0
System.out.println(a[7]); //RTE: ArrayIndexOutOfException
System.out.println(a[-2]); //----do----
System.out.println(a[-2.5]); //CTE: PLP req: int found:double
}
}
4. CLASS CAST EXCEPTION:
Class Sample
{
public static void main(String a[]))
{
String s=”anu”;
Object o=(Object)s;
String s1=(String)O;
System.out.println(“hai”);
}
}
• It is the child class of RTE
• It is unchecked exception, thrown by JVM when attempting to cast a reference variable to a type the fails to cast a reference variable to a type the faith the IS- A test.
----> Object o=new Object();
String s=(String)o; // Class Cast Exception
----> StringBuffer s1= (StringBuffer)s;

5. NOCLASS DEF FOUND ERROR:

  • It is the child class of error and it is unchecked one and unreachable.
  • It is thrown by JVM. If the JVM or class loader tries to load the definition of the class and no definition of the class could be found.
6. EXCEPTION IN INITIALIZER ERROR:
class Sample
{
Static String s;
String s1=new String(s);
public static void main(String a[])
{
System.out.println(“hai”);
}
}//Exception in initializer error caused by java.lang.NullPointerException.
Thrown by the JVM to indicate that an exception is occur during initialization of static variable or initialization block.
7. ILLEGAL ARGUMENT EXCEPTION:
  • It extends RTE and unchecked.
  • Thrown by aPI developer to indicate that a method has been passed an illegal or inappropriate argument.
Ex: Thread class setPriority() and sleep() methods throw this exception.
class Sample
{
p s v m(String a[])
{
Thread.currentThread().setPriority(15);
}
}//CTE: Illegal Argument exception
8. NumberFormatException:
Integer i=new Integer(“10”);//valid
Integer i=new Integer(“ten”);//invalid
CTE: NumberFormateException
int i=Integer.parseInt(arg[0]);
In commandline if we give “10” is valid. But “ten” is invalid.
It is the direct child class of illegal argument exception and thrown programmatically to indicate the application has attempted to convert a string to the number, but the string doesn’t have appropriate format.
9. IllegalStateException:
It extends RTE and indicates that a method has been invoked at an illegal or inappropriate time.
Ex: PrintWriter out=res.getWriter();
Out.println(…);
Out.close();
Out.println(“…”); ---> this is not appropriate time to call print() on out object and hence throws IllegalStateException.
10. Assertion Error:
It is the child class of error throws programatically when assert statement when Assert statement fails.
Summarization:
Exception or error --------------------- thrown by
1. NullPointerException ------------------ JVM
2. StackOverFlowErrorException --------------- JVM
3. ArrayIndexOutOfBoundsException ------------- JVM
4. ClassCastException ------------------------- JVM
5. NoClassDefFoundError -------------------- JVM
6. ExceptionInIntializerError -------------------- JVM

thrown by programmatically by programmer API developer:
7. IllegealArgumentException
8. NumberFormatException
9. IllegalStateException
10. Assertion Error

Checked , Unchecked Exceptions

Checked vs Unchecked Exceptions :
• The Exceptions which are checked by the compiler for smooth execution of program at Runtime are called checked Exceptions.
• The Exceptions which are unable to check by the compiler are called Unchecked Exceptions.
• Runtime Exception and its child classes: Error and its child classes are Unchecked Exceptions. While the remaining all are Unchecked Exceptions.

Partially Checked vs Fully Checked :
A Checked Exception is said to be Fully Checked Exception if and only if all its child classes are also checked. Otherwise it is Partially Checked Exception.
Ex: IOException is Fully Checked Exception
Exception is Partially Checked
Throwable is Partially Checked

try , catch , finally

finally block:
try
{
System.out.println(10/0);
}
catch(AE e)
{
System.out.println(“catch”);
}
finally
{
System.out.println(“catch”);
}
• The cleanup code, we have to keep inside finally block because irrespective of exception occurred or not occurred or handled or not handled, the finally block will always execute.

Q: Difference between final, finally and finalize?
• It is highly recommended to keep cleanup code inside finally block instead of finalize().
• The finally block will always execute except the place where the JVM got shutdown. We can shutdown the JVM by calling /using System.exit(0).

Example:
try

{
System.out.println(“hai”);
}
catch( NULL pointer exception e)
{
System.out.println(“catch”);
}
finally
{
System.out.println(“finally”);
}
output:
hai
finally

Samples:
1. try{} catch(X e){} -->valid

2. try{}catch(X e){}finally{} -->valid
3. try{}finally{}catch(X e){} --> invalid
4. try{}finally{} -->valid
i.e , try --> catch --> finally is the only order.
Only try{} ---> invalid,
Only catch{} ----> invalid
Only finally{} ----> invalid
Note: try without catch & catch with out try invalid

Example:
catch(..){}
finally{}
CTE: catch with out try

Control Flow in try, catch, finally block :
try
{
Stmt1;
Stmt2;
Stmt3;
}
catch(XException e)
{
Stmt 4;
}
finally
{
Stmt 5;
}
Stmt 6;

See the below cases:

Case 1:- If there is no exception then 1,2,3,5,6 and normal termination.
Case 2:- If an exception raised at stmt2 and the corresponding catch block found 1,4,5,6 and normal termination.
Case 3:- If an exception raised at stmt2 and the corresponding catch block not matched 1,5 and abnormal termination.

Control Floe in the Nested try, catch, finally blocks:
try
{
Stmt1;
Stmt2;
Stmt3;
try
{
Stmt4;
Stmt5;
Stmt6;
}catch(XException e)
{
Stmt 7;
}
finally
{
Stmt 8;
}
Stmt 9;
}
catch(YException e)
{
Stmt 10;
}
finally
{
Stmt 11;
}
Stmt 12;

Case 1: If there is no exception 1,2,3,4,5,6,8,9,11,12 and normal termination.
Case 2: If an exception raised at stmt 2 and the corresponding catch block found then 1,10,11,12 and normal termination.
Case 3: If an exception raised at stmt2 and the corresponding catch block has not matched then 1,11 and abnormal termination.
Case 4: If an exception raised at stmt5 and the corresponding catch block has matched then 1,2,3,4,7,8,9,11,12 and normal termination.
Case 5: If an exception raised at stmt5 and the corresponding catch block has not matched but the outer catch has matched then 1,2,3,4,8,10,11,12 and normal termination.
Case 6: If an exception raised at stmt5 but the inner and outer catch blocks are not matched then 1,2,3,4,8,11 and abnormal termination.

‘Throw’ keyword:
public static void main(String a[])
{
try
{
Throw new AithmeticException()
}
}
By using ‘throw ‘ keyword, over created customized exception objects are handed over to JVM.

Example:
class Sample
{
public static void main (String a[])
{
throw new ArithmeticException();
System.out.println(“hai”);
}// CTE: Unreachable statement
}
After throw we are not allowed to keep any statement, violation leads to CTE saying “unreachable statement”.

Example:
class Sample
{
static ArithmeticException e;
public static void main(String[] a)
{
throw e; //invalid
}
}
output: NullPointerException
‘e’(is in instance area) is not pointing “ArithmeticException’ here.
static ArithmeticException e=new ArithmeticException();

Example:
class Sample
{
public static void main(String a[])
{
Throw new Exception(); //invalid
}
}//CTE: “Unreported Exception Java.lang.Exception must be caught” or declared to be thrown.
• Inside a program if there is any chance of throwing a checked exception explicitly or implicitly we have to handle that checked exception by using try - catch or we have to delegate the responsibility or exception handling to the caller. Violation leads to CTE saying Unreported Exception xxx; must be caught or declared to be thrown.

throws , throw

“throws” Keyword :We can ‘throws’ keyword for delegating the responsibility of the Exception handling to the caller.
Ex:
class Sample
{
public static void main(String a[])throws InteruptedException
{
doStuff();
}
public static void doStuff()throws IE
{
doMoreStuff();
}
public static void doMoreStuff()
{
System.out.println(“hai”);
Thread.sleep(1000);
}
}
without ‘throws’ CTE: Unreported Exception java.lang.interuptedException ; must be caught or declared to be thrown. To avoid CTE(compile time error) another way in using try ---> catch block.
Ex:
class Sample
{
public static void main(String a[])
{
try
{
System.out.println(“hello”);
}
catch(IOException e){} --->CTE (fullychecked exception)
}
}
CTE: exception java.io.IOException is never thrown in the body of the corresponding try statement.

  • If we are keeping the catch block for fully checked exception there should may be a chance of raising exception in the corresponding try block otherwise CTE saying XXXException is never thrown in the body of corresponding try statement.
Case 1:
try

{
System.out.println(“hai”);
}
catch(ArithematicException e) //valid no CTE(compile time error)
{ //unchecked exception }
Case 2: try
{
System.out.println(“hai”);
}
catch(Exception e) //valid no CTE
{
//Partially checked exception
}

Case 3:
try

{
System.out.println(“hello”);
}
catch(IOException e) //invalid CTE
{
// fully checked exception
}


Throw keyword:By using ‘throw ‘ keyword, over created customized exception objects are handed over to JVM.

Example:
class Sample
{
public static void main (String a[])
{
throw new ArithmeticException();
System.out.println(“hai”);
}// CTE: Unreachable statement
}
After throw we are not allowed to keep any statement, violation leads to CTE saying “unreachable statement”.

Customized Exceptions :
Based on the programming required sometimes we have to design our own Customized Exceptions.
Ex: Insufficient funds Exception
too young Exception
too old Exception
throw Example:
class TooYoungException extends RunTimeException
{
TooYoungException(String s)
{
super(s);
}
class Sample
{
public static void main(String a[])
{
int i=Integer.parseInt(arg[0]);
if(i>85)
throw new TooYoungException(“please wait some more time, you eill get married”);
else if(i<10)
throw new TooYoungException(“ur age is already crossed”);
else
throw new TooYoungException(“very soon you will get match”);
}
}

Friday, February 6, 2009

java Exception Handling

examples Exception Handling