16-Exceptions Handling java

22
EXCEPTIONS HANDLING

Transcript of 16-Exceptions Handling java

Page 1: 16-Exceptions Handling java

EXCEPTIONS HANDLING

Page 2: 16-Exceptions Handling java

EXCEPTIONS HANDLINGAn exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error.

Java’s exception handling, brings run-time error management into the object oriented world.

Exception-Handling FundamentalsA Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code.

When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error.

Java exception handling is managed via five keywords: try, catch, throw, throws, and

finally.

Page 3: 16-Exceptions Handling java

SCENARIOImagine you’re about to board an airplane to Geneva to attend an important conference.

At the last minute, you learn that the flight has been cancelled because the pilot

isn’t feeling well. Fortunately, the airline quickly arranges for an alternative pilot,

allowing the flight to take off at its originally scheduled time. What a relief.

This example illustrates how exceptional conditions can modify the initial flow of an

action and demonstrates the need to handle those conditions appropriately. In Java,

an exceptional condition (like the illness of a pilot) can affect the normal code flow

(airline flight operation). In this context, the arrangement for an alternative pilot can

be compared to an exception handler.

Depending on the nature of the exceptional condition, you may or may not be able

to recover completely. For example, would airline management have been able to get

your flight off the ground if instead an earthquake had damaged much of the airport?

Page 4: 16-Exceptions Handling java

TYPES OF EXCEPTIONThere are mainly two types of exceptions: checked and unchecked where error is considered as unchecked exception.

1.Checked Exception

2.Unchecked Exception

3.Error

1)Checked Exception

The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at

compile-time.

Page 5: 16-Exceptions Handling java

TYPES OF EXCEPTION2)UnChecked Exception

3)Error

The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.

Unchecked exceptions are not checked at compile-time rather they are checked at runtime.

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Page 6: 16-Exceptions Handling java

EXCEPTION HIERARCHY

All exception classes are subtypes of the java.lang.Exception class.

Throwable

Error Exception

IOException(CHECKED)

RuntimeException(UNCHECKED)

Object

Page 7: 16-Exceptions Handling java

Runtime (Checked Exception)

Checked exceptions are subject to the Catch or Specify Requirement

All exceptions are checked exceptions, except for those indicated by Error, RuntimeException, and their subclasses.

The second kind of exception is the error.

These are exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from.

Page 8: 16-Exceptions Handling java

SCENARIOS WHERE EXCEPTION MAY OCCUR If we divide any number by zero, there occurs an ArithmeticException.

If we have null value in any variable, performing any operation by the variable occurs an NullPointerException.

The wrong formatting of any value, may occur NumberFormatException. Suppose I have a string variable that have characters, converting this variable into digit will occur NumberFormatException

If you are inserting any value in the wrong index, it would result ArrayIndexOutOfBoundsException as shown below:

int a=50/0;//ArithmeticException

String s=null;System.out.println(s.length());//NullPointerException

String s="abc";int i=Integer.parseInt(s);//NumberFormatException

int a[]=new int[5];a[10]=50; //ArrayIndexOutOfBoundsException

Page 9: 16-Exceptions Handling java

Code without Exception Handling

A method catches an exception using a combination of the try and catch keywords. If we donot catch thrown Exception, an abnormal condition occurs and execution stops. 

Result

public class ExcepTest{ public static void main(String args[]){int a[] = new int[2]; System.out.println("Access element three :" + a[3]);System.out.println("Out of the block"); }}

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3at ExcepTest.main(ExcepTest.java:4)

Page 10: 16-Exceptions Handling java

HOW EXCEPTION HANDLING OCCURS

Yes No

a[3]

exception object

Is handled?

JVMPrints Exception Description

Print stacktraceTerminates program

Rest of the code is Executed

Page 11: 16-Exceptions Handling java

Catching Exception A method catches an exception using a combination of

the try and catch keywords. A try/catch block is placed around the code that might generate an exception, if we catch exception thrown the remaining code will also excute.

Result

import java.io.*;public class ExcepTest{ public static void main(String args[]){ try{ int a[] = new int[2]; System.out.println("Access element three :" + a[3]); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Exception thrown :" + e); } System.out.println("Out of the block"); }}

Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3

Out of the block

Page 12: 16-Exceptions Handling java

Multiple catch blockstry{ //Protected code}catch(Exception1 e1){ //Catch block}catch(Exception2 e2){ //Catch block}catch(Exception3 e3){ //Catch block}

try{ //Protected code}catch(Exception1 | Exception2 | Exception2 e1){ //Catch block}

In JD

K 1

.7

Page 13: 16-Exceptions Handling java

At a time only one Exception is occured and at a time only one catch

block is executed.

EXAMPLE OF MULTICATCH

Result

class Excep4{ public static void main(String args[]){ try{ int a[]=new int[5]; a[5]=30/0; } catch(ArithmeticException e){System.out.println("task1 is completed");} catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");} catch(Exception e){System.out.println("common task completed");}

System.out.println("rest of the code..."); }}

task1 completedrest of the code...

Page 14: 16-Exceptions Handling java

MULTICATCH EXAMPLE 2 All catch blocks must be ordered from most specific to most general i.e.

catch for ArithmeticException must come before catch for Exception .

Output:Compile-time error: ArithmeticException already been caught

class Excep4{ public static void main(String args[]){ try{ int a[]=new int[5]; a[5]=30/0; } catch(Exception e){System.out.println("common task completed");} catch(ArithmeticException e){System.out.println("task1 is completed");} catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");} System.out.println("rest of the code..."); }}

Page 15: 16-Exceptions Handling java

NESTED TRY BLOCKpublic class Excep6{ public static void main(String args[]){ try{ try{ System.out.println("going to divide"); int b =39/0; }catch(ArithmeticException e){System.out.println(e);} try{ int a[]=new int[5]; a[5]=4; }catch(ArrayIndexOutOfBoundsException e){System.out.println(e);} System.out.println("other statement"); }catch(Exception e){System.out.println("handeled");}

System.out.println("normal flow.."); }}

Page 16: 16-Exceptions Handling java

finally Block

Yes

NO Yes No

Program Code

Exception Occurred

Exception Handled

Finally Block Executes

finally must be followed by try or

catch block.

For each try block there can be zero or more catch blocks, but only one finally

block.

Note: The finally block will not be executed if program exits(either

by calling System.exit() or by causing a fatal error

that causes the process to abort).

Page 17: 16-Exceptions Handling java

throw KEYWORD

The throw keyword is used to explictily throw an exception.

class Excep13{

static void verify (int age){ if(age<18) throw new ArithmeticException("not valid"); else System.out.println("welcome to vote"); } public static void main(String args[]){ verify(13); System.out.println("rest of the code..."); }}

Output:Exception in thread main java.lang.ArithmeticException:not valid

Page 18: 16-Exceptions Handling java

THROWING OWN USERDEFINED EXCEPTIONSclass InvalidAgeException extends Exception{ InvalidAgeException(String s){ super(s); }}

class Excep13{

static void validate(int age)throws InvalidAgeException{ if(age<18) throw new InvalidAgeException("not valid"); else System.out.println("welcome to vote"); } public static void main(String args[]){ try{ validate(13); }catch(Exception m){System.out.println("Exception occured: "+m);}

System.out.println("rest of the code..."); }}

Output:Exception occured: InvalidAgeException:not valid rest of the code...

Page 19: 16-Exceptions Handling java

throws KEYWORD If you are calling a method that declares an exception, you

must either catch or declare the exception.

import java.io.IOException;class Simple{ void m()throws IOException{ throw new IOException("device error");//checked exception} void n()throws IOException{ m();} void p(){ try{ n(); }catch(Exception e){System.out.println("exception handled");}} public static void main(String args[]){ Simple obj=new Simple(); obj.p(); System.out.println("normal flow..."); }}

Page 20: 16-Exceptions Handling java

CASE1: YOU HANDLE THE EXCEPTIONimport java.io.*;class M{ void method()throws IOException{ throw new IOException("device error"); }}

class Test{ public static void main(String args[]){ try{ M ob=new M(); ob.method(); }catch(Exception e){System.out.println("exception handled");}

System.out.println("normal flow..."); }}

i =i =

Output:exception handled normal flow...

Page 21: 16-Exceptions Handling java

CASE2: YOU DECLARE THE EXCEPTION

import java.io.*;class M{ void method()throws IOException{ System.out.println("device operation performed"); }}

class Test{ public static void main(String args[])throws IOException{//declare exception M ob=new M(); ob.method();

System.out.println("normal flow..."); }}

Output:device operation performed normal flow...

Page 22: 16-Exceptions Handling java

DIFFERENCE BETWEEN THROW AND THROWS:

1. throw is used to explicitly throw an exception.

2. checked exception can not be propagated without throw.

3. throw is followed by an instance.

4. throw is used within the method.

5. You cannot throw multiple exception

1. throws is used to declare an exception.

2. checked exception can be propagated with throws.

3. throws is followed by class.

4. throws is used with the method signature.

5. You can declare multiple exception e.g.public void method()throws IOException,SQLException.