Exceptions & Its Handling

25
Exceptions & its Exceptions & its Handling Handling

Transcript of Exceptions & Its Handling

Page 1: Exceptions & Its Handling

Exceptions & its HandlingExceptions & its Handling

Page 2: Exceptions & Its Handling

What’s this ExceptionWhat’s this Exception

It’s an event, which can occur during the execution of a program, It’s an event, which can occur during the execution of a program, & due to which the normal flow of the program's instructions & due to which the normal flow of the program's instructions may be disrupted.may be disrupted.

Class TestClass Test

{{

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

{{

System.out.println( 6/0 );System.out.println( 6/0 );

System.out.println( “Hello” );System.out.println( “Hello” );

// do something else// do something else

}}

}}Exception in thread "main" java.lang.ArithmeticException: / by zeroException in thread "main" java.lang.ArithmeticException: / by zero

at NewClass.main(NewClass.java:20)at NewClass.main(NewClass.java:20)

Page 3: Exceptions & Its Handling

Throwing an ExceptionThrowing an Exception

When an error occurs within a method, the run-time system When an error occurs within a method, the run-time system creates an object and hands it off to the method. The object, creates an object and hands it off to the method. The object, called an exception object, contains information about the error, called an exception object, contains information about the error, including its type and the state of the program when the error including its type and the state of the program when the error occurred. Creating an exception object and handing it to the occurred. Creating an exception object and handing it to the relevant method is called throwing an exception.relevant method is called throwing an exception.

After a method throws an exception, the runtime system After a method throws an exception, the runtime system attempts to find the ordered list of methods that had been called attempts to find the ordered list of methods that had been called to get to the method where the error occurred. The list of to get to the method where the error occurred. The list of

methods is known as the methods is known as the call stackcall stack

Page 4: Exceptions & Its Handling

Understanding the Call StackUnderstanding the Call Stack

Exception in thread "main" java.lang.ArithmeticException: / by zeroException in thread "main" java.lang.ArithmeticException: / by zero at NewClass.y(NewClass.java:23)at NewClass.y(NewClass.java:23) at NewClass.x(NewClass.java:21)at NewClass.x(NewClass.java:21) at NewClass.main(NewClass.java:19)at NewClass.main(NewClass.java:19)

y(), where exception occured

x()

main()

Class TestClass Test

{{

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

{ x(); }{ x(); }

void x()void x()

{ y(); }{ y(); }

void y()void y()

{ int a = 7/0; }{ int a = 7/0; }

}}

Page 5: Exceptions & Its Handling

Exception HandlerException Handler

The runtime system searches the call stack for a method that contains a block The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an of code that can handle the exception. This block of code is called an exception handler.exception handler.

The search begins with the method in which the error occurred and proceeds The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were through the call stack in the reverse order in which the methods were called. called.

When an appropriate handler is found, the runtime system passes the When an appropriate handler is found, the runtime system passes the exception object to the handler.exception object to the handler.

An exception handler is considered appropriate if the type of the exception An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler. object thrown matches the type that can be handled by the handler.

Page 6: Exceptions & Its Handling

Searching for the Exception Handler in Searching for the Exception Handler in the call stackthe call stack

If main forwarded the exception, the thread will abnormally terminate.If main forwarded the exception, the thread will abnormally terminate.

y(), where exception occured

x()

main()

throws exception

should handle but may forward exception

Looking for appropriate handler

Looking for appropriate handler

should handle but may forward exception

Page 7: Exceptions & Its Handling

Catch or Specify RequirementCatch or Specify Requirement

The code that might throw certain exception must be enclosed The code that might throw certain exception must be enclosed either by :either by :

A try statement that catches the exception. The try must provide a handler A try statement that catches the exception. The try must provide a handler for the exception. for the exception.

A method that specifies that it can throw the exception. The method must A method that specifies that it can throw the exception. The method must provide a throws clause that lists the exception. provide a throws clause that lists the exception.

Code that fails to honor the Catch or Specify requirement will Code that fails to honor the Catch or Specify requirement will not compile. not compile.

Not all exceptions are subject to the Catch or Specify Not all exceptions are subject to the Catch or Specify requirement. requirement.

Page 8: Exceptions & Its Handling

Exception Types : 3Exception Types : 3

Checked ExceptionChecked Exception

Run-time ExceptionRun-time Exception

ErrorErrorUnChecked ExceptionUnChecked Exception

Page 9: Exceptions & Its Handling

Class HierarchyClass Hierarchy

java.lang.Object

java.lang.Throwable

java.lang.Error java.lang.Exception

java.lang.RuntimeException

Page 10: Exceptions & Its Handling

Checked ExceptionChecked Exception

An exceptional condition that a well-written application should An exceptional condition that a well-written application should anticipate and recover from. anticipate and recover from.

java.io.FileNotFoundException java.io.FileNotFoundException Java.io.IOExceptionJava.io.IOException Java.io.InterruptedExceptionJava.io.InterruptedException

Checked exceptions Checked exceptions are subjectare subject to the Catch or Specify to the Catch or Specify Requirement.Requirement.

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

Page 11: Exceptions & Its Handling

Runtime ExceptionRuntime Exception Exceptional conditions that are internal to the application, and that Exceptional conditions that are internal to the application, and that

the application usually cannot anticipate. the application usually cannot anticipate.

Usually indicate programming bugs, such as logic errors or Usually indicate programming bugs, such as logic errors or improper use of an API. improper use of an API.

Runtime exceptions Runtime exceptions are not subjectare not subject to the Catch or Specify to the Catch or Specify requirement. Runtime exceptions are those indicated by requirement. Runtime exceptions are those indicated by RuntimeException and its subclasses. RuntimeException and its subclasses.

Ex :- Ex :- java.lang.NullPointerExceptionjava.lang.NullPointerException java.lang.ArrayIndexOutOfBoundsExceptionjava.lang.ArrayIndexOutOfBoundsException java.lang.ArithmeticExceptionjava.lang.ArithmeticException

Page 12: Exceptions & Its Handling

ErrorError

Exceptional conditions that are external to the application, and that Exceptional conditions that are external to the application, and that the application usually cannot anticipate. the application usually cannot anticipate.

Ex :- java.io.IOErrorEx :- java.io.IOError

Errors Errors are not subjectare not subject to the Catch or Specify Requirement. to the Catch or Specify Requirement.

Errors are those exceptions indicated by Error and its subclasses. Errors are those exceptions indicated by Error and its subclasses.

Page 13: Exceptions & Its Handling

Runtime Exception due to Logical Errors Runtime Exception due to Logical Errors

public class NewClass public class NewClass

{ {

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

{{

int array[] = {6,7,8,9,10};int array[] = {6,7,8,9,10};

for(int index=0; index<array.length+2; index++)for(int index=0; index<array.length+2; index++)

System.out.print(array[index]+” “);System.out.print(array[index]+” “);

System.out.println("After loop");System.out.println("After loop");

}}

}}

6 7 8 9 106 7 8 9 10

Exception in thread "main"java.lang.ArrayIndexOutOfBoundsException: 5 at Exception in thread "main"java.lang.ArrayIndexOutOfBoundsException: 5 at NewClass.main(NewClass.java:22)NewClass.main(NewClass.java:22)

Page 14: Exceptions & Its Handling

Runtime Exception due to Logical ErrorsRuntime Exception due to Logical Errors

public class NewClass public class NewClass { {

static Integer i;static Integer i; public static void main(String[] args)public static void main(String[] args) {{ System.out.println("1st statement");System.out.println("1st statement"); System.out.println(i.intValue());System.out.println(i.intValue()); System.out.println("3rd Statement");System.out.println("3rd Statement"); show("tom");show("tom"); }} static void show(String msg)static void show(String msg) {{ System.out.println(msg.toUpperCase());System.out.println(msg.toUpperCase()); }}}}

1st statement1st statement

Exception in thread "main" java.lang.NullPointerException at Exception in thread "main" java.lang.NullPointerException at NewClass.main(NewClass.java:21)NewClass.main(NewClass.java:21)

Page 15: Exceptions & Its Handling

Runtime Exception due to improper use of APIRuntime Exception due to improper use of API

class Test{

static Thread t2;public static void main(String[] args){

Thread t1 = new Thread(){

public void run(){

for(int i=0; i<10; i++)System.out.print(“ new

thread ”);}

};t1.start(); t2.start();for(int i=0; i<5; i++)System.out.print(“ Main thread ”);

}}

Exception in thread "main" java.lang.NullPointerException at NewClass.main(NewClass.java:30) new thread new thread new thread new thread new thread new thread new thread new

thread new thread new thread

Page 16: Exceptions & Its Handling

Runtime Exception due to improper use of APIRuntime Exception due to improper use of API

class Testclass Test{{

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

System.out.println(“First statement”);System.out.println(“First statement”);m(“india”);m(“india”);m(35);m(35);System.out.println(“Last statement”);System.out.println(“Last statement”);

}}static void m(Object o)static void m(Object o){{

Integer i = (Integer)o;Integer i = (Integer)o;}}

}}First statementFirst statementException in thread "main" java.lang.ClassCastException: java.lang.StringException in thread "main" java.lang.ClassCastException: java.lang.String at Test.m(NewClass.java:27) at Test.m(NewClass.java:27) at Test.main(NewClass.java:21) at Test.main(NewClass.java:21)

Page 17: Exceptions & Its Handling

Dealing with ExceptionDealing with Exception Using try & catch block of code.Using try & catch block of code.

public class NewClass public class NewClass

{ {

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

{{

int array[] = {6,7,8,9,10};int array[] = {6,7,8,9,10};

try{try{

for(int index=0; index<array.length+2; index++)for(int index=0; index<array.length+2; index++)

}}

catch(Exception e)catch(Exception e)

{ { System.out.println(“Element with this index doen’t exist”); System.out.println(“Element with this index doen’t exist”); }}

System.out.print(array[index]+” “);System.out.print(array[index]+” “);

System.out.println("After loop");System.out.println("After loop");

}}

}}

Page 18: Exceptions & Its Handling

try{try{ System.out.println(9/0);System.out.println(9/0);

System.out.println("Hello");System.out.println("Hello"); }} catch(Exception e)catch(Exception e) {{ System.out.println(e.getMessage());System.out.println(e.getMessage()); return;return; }}

System.out.println("Last statement");System.out.println("Last statement");

Page 19: Exceptions & Its Handling

Using finally blockUsing finally block

try{try{ System.out.println(9/0);System.out.println(9/0); System.out.println("Hello");System.out.println("Hello"); }} catch(Exception e)catch(Exception e) {{ System.out.println(e.getMessage());System.out.println(e.getMessage());

return;return; }} finally{System.out.println("2nd Last statement");}finally{System.out.println("2nd Last statement");} System.out.println("Last statement");System.out.println("Last statement");

Page 20: Exceptions & Its Handling

java.lang.Object

java.lang.Throwable

java.lang.Exception

java.lang.RuntimeExceptionIndexOutOfBoundsException

ArrayIndexOutOfBoundsException

StringIndexOutOfBoundsException

Page 21: Exceptions & Its Handling

int arr[] = {5,6,7};int arr[] = {5,6,7}; try{try{ System.out.println(arr[5]);System.out.println(arr[5]); }} catch(Exception e)catch(Exception e) {{ System.out.println("first catch");System.out.println("first catch"); }} catch(RuntimeException re)catch(RuntimeException re) {{ System.out.println("2nd catch");System.out.println("2nd catch"); }}

Page 22: Exceptions & Its Handling

public static void main(String[] args)public static void main(String[] args){{ System.out.println(m()); System.out.println(m()); }}static int m()static int m(){{ trytry {{ int x = 7/0;int x = 7/0; return x;return x; }} catch(Exception e)catch(Exception e) {{ System.out.println("catch block");System.out.println("catch block"); return 0;return 0; }} finallyfinally {{ System.out.println("finally block");System.out.println("finally block"); return 1;return 1; }}}}

Page 23: Exceptions & Its Handling

Handling Checked ExceptionsHandling Checked Exceptionspublic static void main(String[] args)public static void main(String[] args){{

m(); m();

}}static void m()static void m(){{

FileInputStream fis = new FileInputStream("abc.java");FileInputStream fis = new FileInputStream("abc.java");

}}

try{try{

}}catch(FileNotFoundException e)catch(FileNotFoundException e){ //….. }{ //….. }

throws FileNotFoundExceptionthrows FileNotFoundException

try{try{

}}catch(IOException e)catch(IOException e){ //….. }{ //….. }

throws FileNotFoundExceptionthrows FileNotFoundException

Page 24: Exceptions & Its Handling

Creating Custom UnChecked ExceptionsCreating Custom UnChecked Exceptions

public class NewClass public class NewClass

{ {

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

{{

m(); m();

} }

static void m()static void m()

{ {

throw new MyException();throw new MyException();

}}

}}

class MyException extends RuntimeExceptionclass MyException extends RuntimeException

{{

MyException()MyException()

{ super("This is my exception"); }{ super("This is my exception"); }

}}

Exception in thread "main" Pack.MyException: This is my exceptionException in thread "main" Pack.MyException: This is my exception

at NewClass.m(NewClass.java:24)at NewClass.m(NewClass.java:24)

at NewClass.main(NewClass.java:20)at NewClass.main(NewClass.java:20)

Page 25: Exceptions & Its Handling

Creating Custom Checked ExceptionsCreating Custom Checked Exceptions

public static void main(String[] args)public static void main(String[] args){{ m(); m(); } } static void m()static void m(){{ throw new MyException();throw new MyException();}}class MyException extends RExceptionclass MyException extends RException{{ MyException()MyException() {{ super("This is my exception");super("This is my exception"); }}}}