Exception Handling in Java

Post on 22-Jan-2017

209 views 0 download

transcript

Exception - Handling

WHAT IS EXCEPTION?The Unwanted event that occurred at runtime and disturbs the Normal flow of program is called “Exception”

The process of handling the Exceptions is called

“Exception Handling”

DIFFERENCE BETWEEN ERROR AND EXCEPTIONError : Error is a problem for which we are unable to provide the solution programmaticallyEx: Linkage Error , Virtual Machine Error

Exception : Exception is a problem for which we are able to provide the Solution(Alternative)Ex: IOException , NullPointer Exception

We are not repairing the Exception

TYPES OF TERMINATIONS IN THE APPLICATIONSSmooth termination

Terminating the application at the end of the program After completing the execution is called Smooth termination

AbNormal TerminationTerminating the application , while in the execution of

the application due to some events is called AbNormal Termination

TYPES OF EXCEPTIONS IN JAVA1.Checked Exceptions

2.Unchecked Exceptions.

Even though exceptions arrives at runtime compiler is able to warn about some kind of exceptions when there is exception prone code at compile time.i.e., Exceptions that are checked at compile-time are Checked-ExceptionsExamples of Checked Exceptions:IOExceptionSQLException etc.

Exceptions that are not checked at compile-time are Unchecked-ExceptionsExamples of Unchecked Exceptions:NullPointerExceptionArrayIndexOutOfBoundIllegalArgumentException etc.

EXCEPTION HIERARCHY

Importance of try , catch , finally

Try{

}

catch() // Handling Code}

finally{// Clean up code

}

// Risky Code

POINT TO BE REMEMBER…………..

With In the try block If Exception is Raised , then rest of the try block won’t be executed even though we handle that exception

DISPLAYING THE EXCEPTION DETAILS1. PrintStackTrace()

2.toString()

3.getMessage()

1. PrintStackTrace()

Name of the ExceptionDescription of the ExceptionLocation o the Exception

2.toString()Name of the ExceptionDescription of the Exception

3.getMessage()

Description of the Exception

CONTROL-FLOW IN TRY & CATCH

Try{statement 1;statement 2;statement 3;

}

Catch(Exception e){statement 4;

}

statement 5;

Try{statement 1;statement 2;statement 3;

}

Catch(Exception e){statement 4;

}

statement 5;

Case 1: If there is no Exception

Statements executed

statement 1;statement 2;statement 3;statement 5;

Normal

Try{statement 1;statement 2;statement 3;

}Catch(Exception e){

statement 4;}statement 5;

Case 2: Exception is raised at statement2 & is Handled(catch block is matched)

Statements executed

statement 1;statement 4;statement 5;

Normal

Try{statement 1;statement 2;statement 3;

}Catch(Exception e){

statement 4;}statement 5;

Case 3 : Exception is raised at statement2 & corresponding catch block is not provided

Statements executed

only statement 1;

Ab-Normal

Try{statement 1;statement 2;statement 3;

}

Catch(Exception e){statement 4;

}

statement 5;

Case 4 Exception is raised at statement4 (or) statement5

Statements executed

Up to Preceding statement before Exception

Ab-Normal

POINT TO BE REMEMBER…………..

If any Exception is raised outside the try block , it is always leads to the AbNormal termination of the program

finally block

finally block is always associated with try & catch

It can be used to execute a set of instructions irrespective of that ,whether the exception occurred or not and that exception is handled or not

Always finally block is executed

class Test1{

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

Try{System.out.println(“try”);

}

catch(Exception e){System.out.println(“catch”);

}finally{

System.out.println(“finally”);}

}

}

outputtryfinally

Control-Flow in try , catch & finally

Try{statement 1;statement 2;statement 3;

}Catch(Exception e){

statement 4;}finally{

statement 5;}

statement 6;

Try{statement 1;statement 2;statement 3;

}Catch(Exception e){

statement 4;}

statement 6;

Case 1: If there is no Exception

Statements executed

statement 1;statement 2;statement 3;statement 5;

Normalfinally{ statement 5;

}

statement 6;

Try{statement 1;statement 2;statement 3;

}Catch(Exception e){

statement 4;}

statement 6;

Case 2 Exception is raised at statement2 & corresponding catch block is matched

Statements executed

statement 1;statement 4;statement 5;

Normalfinally{ statement 5;

}

statement 6;

Try{statement 1;statement 2;statement 3;

}Catch(Exception e){

statement 4;}

statement 6;

Case 3 Exception is raised at statement2 & corresponding catch block is not matched

Statements executed

statement 1;statement 5;

Ab-Normal

finally{ statement 5;

}

Try{statement 1;statement 2;statement 3;

}Catch(Exception e){statement 4;

}

statement 6;

Case 4 Exception is raised at statement4 i.e. , the Exception already occurred at statement1 or statement2 or statement 3

Statements executed

Ab Normalfinally{

statement 5;}

Up to Preceding statement before Exception Statement 5

Try{statement 1;statement 2;statement 3;

}Catch(Exception e){statement 4;

}

statement 6;

Case 5 Exception is raised at statement5 (or) statement6

Statements executed

Ab Normalfinally{

statement 5;}

Up to Preceding statement before Exception Statement 5

class Test1{

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

Try{System.out.println(10/0);System.out.println(“try”);

}catch(ArrayIndexOutOfBoundsException e){

System.out.println(“catch”);}finally{

System.out.println(“finally”);}

}}

outputFinallyException in Thread ……

System.out.println(“out side finally”);

‘finally’ dominates the return statement also

class Return{ public static void main(String as[]) { try{ System.out.println("try"); return; } catch(Exception e){ System.out.println("catch"); } finally{ System.out.println("fanally"); } System.out.println("outside finally");

}}

finally won’t executed in only one situation

If we shutdown the jvm , finally not executed

class Shutdown{

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

Try{System.out.println(“try”); System.exit(0);

}catch(Exception e){

System.out.println(“catch”);}finally{

System.out.println(“finally”);}

}}

output

try

System.out.println(“out side finally”);

Is it possible to write try , catch finally inside any of these blocks??

Yes, Absolutely possible

Inside the try block

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

finally{}

}catch(Exception e){} finally{}

public static void main(String args[]){

}

Inside the catch block

try{}catch(Exception e){

try{}catch(Exception e){}

finally{}

} finally{}

public static void main(String args[]){

}

Inside the finally block

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

try{}catch(Exception e){}

finally{}

}

public static void main(String args[]){

}

try with multiple catchesThe way handling the Exception is varied from Exception to Exception

Hence for every Exception , it is highly recommended to write a separate catch block

Syntax : try{}catch(Exception e1){} catch(Exception e2){}catch(Exception e3){}

POINT TO BE REMEMBER ……

In this case the order of catch block is very important

It should be from child to parent

If we will place them in the order from parent to childC.T.E : “Exception ExceptionName has already been caught

Animal

Pet Animal Wild Animal

DOG

CAT TIGER

LION

Send Try{

}catch(Dog ){

Sopln(“It is a Dog”);}

catch(Cat ){Sopln(“It is a cat”);

}

catch(Tiger){Sopln(“It is a tiger”);

}

catch(Wild Animal){Sopln(“It is a Wild

Animal”);}

catch(Animal ){Sopln(“It is a Animal”);

}

Dog It is a Dog

Output

Send Try{

}

catch(Dog )Sopln(“It is a Dog”);

}

catch(Cat )Sopln(“It is a cat”);

}

catch(Wild Animal)Sopln(“It is a Wild

Animal”);}

catch(Lion)Sopln(“It is a Lion”);

}

catch(Animal ){Sopln(“It is a Animal”);

}

Dog It is a Animal

Output

Class Test3{public static void main(String args[]){

try{int[] a=newint[3];a[0]=1;a[100]=2;

}catch(Exception e){

System.out.println(“Exception”);}catch(ArrayIndexOutOfBoundsException e){

System.out.println(“AIOOBE”);}

}}

C.T.E The Exception has already been caught

DEFAULT EXCEPTION HANDLING IN JAVAIf in any method an Exception is raised , then that method is responsible for creation of the Exception object by including the Exception details

After creating the Exception object , the method handovers that Object to the jvm

The jvm checks for the Exception handling code in that method

If it is available , then jvm continues the rest of program execution After executing handling code

If it is not available , jvm terminates the execution abnormally & removes the corresponding entry from the stack

Just before terminating the program abnormally , jvm handovers the responsibility of Exception handling to Default Exception Handler

Default Exception Handler just print the Exception information on the console in the following formatName of the Exception : DescriptionStack Trace(Location o the Exception)

class Test1{

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

System.out.println(10/0);

}

}

throws The main purpose of the throws keyword is to bypass the Exception handling from current method to caller if we are not interested to handle it

class Throws2{

public static void m1(){ m2();} public static void m2(){ System.out.println(10/0);} public static void main(String args[]){ Throws2.m1();}

}

class Throws2{

public static void m1(){ m2();} public static void m2(){ System.out.println(10/0);} public static void main(String args[]){ Throws2.m1();}

}

throw The main purpose of the throw key word is to raise the Exception intentionally based on our application requirement

Point to be remember ……

After using the “throw” statement , If we will use any other statements ,then we will get compile-time error

Example :

Public static void main(String args[]){throw new ArithmeticException(“My Exception”)System.out.println(“Hello”);

}

class A{

}

C.T.E : Unreachable statementSystem.out.println(“Hello”);

STEPS TO CREATE USER DEFINED EXCEPTIONS

There are 3 steps to create to create user defined Exceptions

STEP-1 : Create one user defined Exception class as a child class to

java.lang.Throwable

java.lang.Exception

C lass InvalidMarks extends Exception{

}

STEP-2 : Prepare One String Parametrized constructor (To hold

the Exception Details) With the “super” statement

Class InvalidMarks extends Exception {

InvalidMarks(String s){super(s);

}}

STEP-3 : Raise the Exception intentionally based on our

application requirement

If(smarks<0 || smarks>100){

throw new InvalidMarks(“Marks are Invalid”);

}

Presentation ByGanesh Kumar Reddy