Download JavaWorkshop_ExceptionHandling

Document related concepts
no text concepts found
Transcript
Deen Dayal Upadhyaya College
Department of Computer Science
Workshop on Java J2SE
Exception Handling
Ankit Rajpal
Assistant Professor
Dept. of Computer Science
DDUC
1
What is an Exception?
An exception is an abnormal condition in which
the normal execution of code gets hampered.
Example
double division(double a, double b)
{
double c=a/b;
return c;
}
2
What is an Exception?
• Exception occurs in run time during the
program execution.
• Keywords:
–
–
–
–
–
try
catch
finally
throw
throws
3
Exception Handling
• Exception is handled by five keywords:
i. try
ii. catch
iii. finally
iv. throw
v. throws
Code that may produce an exception is placed under
try block.
4
Exception Handling
• Exception is handled by five keywords:
i. try
ii. catch
iii. finally
iv. throw
v. throws
catch block is used to handle the Exception.
5
Exception Handling
• Exception is handled by five keywords:
i. try
ii. catch
iii. finally
iv. throw
v. throws
If some necessary code is to be executed after try block
then it is placed inside finally block.
6
Exception Handling
• Exception is handled by five keywords:
i. try
ii. catch
iii. finally
iv. throw
v. throws
By the help of throw keyword programmer generates
the Exception.
7
Exception Handling
• Exception is handled by five keywords:
i. try
ii. catch
iii. finally
iv. throw
v. throws
When an Exception in thrown out of a method throws
keyword is used. It appears :
• after method’s parameter list and ,
• before the method’s body
8
Hierarchy
9
Errors
• Errors are thrown by the Java run time system
and indicate some irrecoverable conditions that
occur during the program execution.
• Once thrown by the system, the application
cannot recover from it and will come to halt.
• Errors need not be handled (Catched)
Example
• java.lang.OutofMemoryError
• java.lang.StackOverflowError
10
Errors
public class ErrorDemo
{
public void method1()
{
this.method2();
}
public void method2()
{
this.method1();
}
public static void main(String args[])
{
ErrorDemo ed=new ErrorDemo();
ed.method1();
Exception in thread "main"
}
java.lang.StackOverflowError
}
at ErrorDemo.method2(ErrorDemo.java:10)
at ErrorDemo.method1(ErrorDemo.java:6)
at ErrorDemo.method2(ErrorDemo.java:10)
at ErrorDemo.method1(ErrorDemo.java:6)
11
……..
Some Java Exception Classes
12
Some Java Exception Classes (cont.)
13
Exception
• Unlike Errors, Exception can be handled to
prevent the program to automatically
terminate.
• Exceptions can be handled using the try
and catch blocks.
14
Default Handler
class Exc0
{
public static void main(String args[])
{
int d = 0;
int a = 42 / d;
}
}
java.lang.ArithmeticException: / by zero
at Exc0.main(Exc0.java:6)
15
Exception Handler
Exception
"thrown" here
Thrown exception matched against first
set of exception handlers
Exception
handler
If it fails to match, it is matched against
next set of handlers, etc.
Exception
handler
If exception matches none of handlers,
program is abandoned
16
try, catch and finally
• The code which might throw some exceptions
should be kept in try block.
• The catch block can have the code to handle
the exception or log the same.
• finally block can be used to clean up code or
release some resources that are utilized in the
program.
17
Syntax
try
{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb)
{
// exception handler for ExceptionType2
}
// ...
finally
{
// block of code to be executed after try block ends
}
18
Execution Sequence
Suppose no exceptions in
the statements
try
{
statements;
}
catch(TheException ex)
{
handling ex;
}
finally
{
finalStatements;
}
Next statement;
19
Execution Sequence
try
{
statements;
}
try {
statements;
catch(TheException
ex)
}
{
catch(TheException
ex) {
handling ex;
} handling ex;
}
finally
finally {
{ finalStatements;
} finalStatements;
}
Next statement;
Next statement;
20
The final block is always
executed
Execution Sequence
try
{
statements;
}
catch(TheException ex)
{
handling ex;
}
finally
{
finalStatements;
}
Next statement;
Next statement in the
method is executed
21
Execution Sequence
try
{
statement1;
statement2;
statement3;
}
catch(Exception1 ex)
{
handling ex;
}
finally
{
finalStatements;
}
Next statement;
Suppose an exception of type
Exception1 is thrown in
statement2
22
Execution Sequence
try
{
statement1;
statement2;
statement3;
}
catch(Exception1 ex)
{
handling ex;
}
finally
{
finalStatements;
}
Next statement;
The exception is handled.
23
Execution Sequence
try
{
statement1;
statement2;
statement3;
}
catch(Exception1 ex)
{
handling ex;
}
finally
{
finalStatements;
}
The final block is always
executed.
Next statement;
24
Execution Sequence
try
{
statement1;
statement2;
statement3;
}
catch(Exception1 ex)
{
handling ex;
}
finally
{
finalStatements;
}
The next statement in the
method is now executed.
Next statement;
25
26
27
Example
class Exc2
{
public static void main(String args[])
{
int d, a;
try
{ // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e)
{ // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
28
try, catch and finally-Rules
• When there is a try block, catch or finally block
should be there.
• There should not be any statements between try
and catch and finally.
• finally block is always optional.
• There can be multiple catch blocks for a try block.
• There should be only finally block for a try block.
• catch block is executed only when an exception is
thrown.
29
try, catch and finally-Rules
• The narrow exceptions should be declared
first and the broader exceptions last.
• Incase of multiple catch blocks, exceptions
of a subclass type should be placed before
exceptions of a superclass type.
– Otherwise, the catch block containing the
subclass type will never be executed.
• Finally block always runs even when there
is no exception occurs.
• When an exception is thrown, the rest of
lines of code in try block will not get
executed and the control directly goes for
catch or finally.
30
31
class SuperSubCatch
{
public static void main(String args[])
{
try
{
int a = 0;
int b = 42 / a;
}
catch(Exception e)
{
System.out.println("Generic Exception catch.");
}
catch(ArithmeticException e)
{
System.out.println("This is never reached.");
}
}
}
32
class A
{
}
public class ClassNotFoundDemo
{
public double division(double a,double b)
{
double c=0;
try
{
c=a/b;
Class cl=Class.forName("A");
System.out.println(cl.getName());
cl=Class.forName("java.lang.String");
System.out.println(cl.getName());
cl=Class.forName("Hello");
System.out.println("It might not run");
}
33
catch(ArithmeticException e)
{
System.out.println(e.getMessage());
}
catch(ClassNotFoundException ce)
{
System.out.println(ce.toString());
}
return c;
}
public static void main(String args[])
{
ClassNotFoundDemo demo=new ClassNotFoundDemo();
demo.division(15,2);
}
}
A
java.lang.String
java.lang.ClassNotFoundException: Hello
34
Exception Propagation
• Method call Stack
35
Exception Propagation
• Method call Stack
36
Exception Propagation
• Method call Stack
37
Exception Propagation
• Method call Stack
If not handled in any method, the exception
is thrown and application will stop.
38
The Method printStackTrace
• Used to determine the order in which the methods
were called and where the exception was handled.
• Java keeps track of the sequence of method calls in a
program. When an exception occurs in a method,
you can invoke the method printStackTrace()
(which comes courtesy of the Throwable class) to
determine the order in which the methods were
called and where the exception was handled.
39
The Method printStackTrace
(continued)
import java.io.*;
public class PrintStackTraceExample1
{
public static void main(String[] args)
{
try
{
method1();
}
catch (Exception e)
{
System.out.println(e.toString()
+ " caught in main");
e.printStackTrace();
}
}
40
The Method printStackTrace
(continued)
public static void method1() throws Exception
{
method2();
}
public static void method2() throws Exception
{
method3();
}
public static void method3() throws Exception
{
throw new Exception("Exception generated "
+ "in method C");
}
}
41
The Method printStackTrace
• Sample Run
java.lang.Exception: Exception generated in method C caught in main
java.lang.Exception: Exception generated in method C
at PrintStackTraceExample1.methodC (PrintStackTraceExample1.java:30)
at PrintStackTraceExample1.methodB (PrintStackTraceExample1.java:25)
at PrintStackTraceExample1.methodA (PrintStackTraceExample1.java:20)
at PrintStackTraceExample1.main (PrintStackTraceExample1.java:9)
Note: Because the methods 1 and 2 do not handle the exception
thrown by method3, they (1 and 2) must include the ‘throws’
clause in their heading.
42
Three kinds of Exceptions
• Checked Exception
– These are exceptional conditions that a well-written
application should anticipate and recover from.
Unchecked Exception
• For example, a FileNotFoundException is a checked
exception, and is generated when you write code that is supposed
to open a file for reading or writing.
• Error
– These are exceptional conditions that are external to the
application, and that the application usually cannot anticipate
or recover from.
• Runtime Exception
– These are exceptional conditions that are internal to the
application, and that the application usually cannot anticipate
or recover from.
• For example, the nextInt() method of the Scanner class
throws un-checked exceptions which is why we haven’t had to write
code to handle them.
43
Checked Exception: “Catch or Declare”
Option 1: Catch the exception:
Enclosing the code inside a try block and handling the
code via a catch and/or finally block(s).
Option 2: Declare via a ‘throws’ clause.
The throws clause is part of your method signature.
This clause indicates that the code inside your method
may generate an exception, but that your method does not
handle that exception (or handles it incompletely).
44
Unchecked Exceptions
• Exceptions that can only be recognized at “run-time” (when the
program is being executed). For example, code that requires user
input.
– These must be checked for by programmer
• All subclasses of RuntimeException are unchecked exceptions
• Examples
– Division by zero
– Array index out of bounds
When the program is being compiled, it may not be possible for the
compiler to know if a division by zero will occur. Therefore, the
compiler does not check for this exception at compile-time.
45
Declaring Exceptions
Every method must state the types of checked
exceptions it might throw. This is known as
declaring exceptions.
public void myMethod()
throws IOException
public void myMethod()
throws IOException, OtherException
46
Execution Sequence
try
{
statement1;
statement2;
statement3;
}
catch(Exception1 ex)
{
handling ex;
}
catch(Exception2 ex)
{
handling ex;
throw ex;
}
finally
{
finalStatements;
}
statement2 throws an
exception of type Exception2.
Next statement;
47
Execution Sequence
try
{
statement1;
statement2;
statement3;
}
catch(Exception1 ex)
{
handling ex;
}
catch(Exception2 ex)
{
handling ex;
throw ex;
}
finally
{
finalStatements;
}
Handling exception
Next statement;
48
Execution Sequence
try
{
statement1;
statement2;
statement3;
}
catch(Exception1 ex)
{
handling ex;
}
catch(Exception2 ex)
{
handling ex;
throw ex;
}
finally
{
finalStatements;
}
Execute the final block
Next statement;
49
Execution Sequence
try
{
statement1;
statement2;
statement3;
}
catch(Exception1 ex)
{
handling ex;
}
catch(Exception2 ex)
{
handling ex;
throw ex;
}
finally
{
finalStatements;
}
Next statement;
Rethrow the exception and
control is transferred to the
caller
50
51
52
Throwing Exceptions
When the program detects an error, the program
can create an instance of an appropriate exception
type and throw it. This is known as throwing an
exception. Here is an example,
throw new TheException();
TheException
throw ex;
ex
=
new
53
TheException();
Declaring, Throwing, and Catching
Exceptions
declare exception
method1() {
method2() throws Exception {
try {
invoke method2;
}
catch (Exception ex) {
Process exception;
}
catch exception
if (an error occurs) {
throw new Exception();
}
}
}
54
throw exception
Catching Exceptions
main method {
...
try {
...
invoke method1;
statement1;
}
catch (Exception1
ex1) {
Process ex1;
}
statement2;
}
method1 {
...
try {
...
invoke method2;
statement3;
}
catch (Exception2
ex2) {
Process ex2;
}
statement4;
}
55
method2 {
...
try {
...
invoke method3;
statement5;
}
catch (Exception3
ex3) {
Process ex3;
}
statement6;
}
An
exception
is thrown
in
method3
import java.io.FileNotFoundException;
import java.io.FileReader;
class throwsDemo
{
void Demo() throws FileNotFoundException
{
FileReader fr=new FileReader("test.txt");
}
public static void main(String args[])
{
throwsDemo td=new throwsDemo();
td.Demo(); //Unhandled exception type FileNotFoundException
}
}
56
57
Catch or Declare Checked Exceptions
Java forces you to deal with checked exceptions. If a method declares a
checked exception (i.e., an exception other than Error or
RuntimeException), you must invoke it in a try-catch block or declare to
throw the exception in the calling method. For example, suppose that
method p1 invokes method p2 and p2 may throw a checked exception (e.g.,
IOException), you have to write the code as shown in (a) or (b).
void p1() {
try {
p2();
}
catch (IOException ex) {
...
}
}
void p1() throws IOException {
p2();
}
(a)
(b)
58
Example: Declaring, Throwing, and
Catching Exceptions
• Objective: This example demonstrates
declaring, throwing, and catching exceptions
by modifying the setRadius method in the
Circle class. The new setRadius method
throws an exception if radius is negative.
TestCircleWithException
59
Constructors and Methods of Class
Throwable
60
Creating Your Own Exception Classes
class MyException extends Exception
{
int detail;
MyException(int a)
{
detail = a;
}
public String toString()
{
return "MyException[" + detail + "]";
}
}
class ExceptionDemo
{
static void compute(int a) throws MyException
{
System.out.println("Called compute(" + a + ")");
61
Creating Your Own Exception Classes
if(a > 10)
throw new MyException(a);
System.out.println("Normal exit");
}
public static void main(String args[])
{
try
{
compute(1);
compute(20);
}
catch (MyException e)
{
System.out.println("Caught " + e);
}
}
}
62
63
Cautions When Using Exceptions
• Exception handling separates error-handling
code from normal programming tasks, thus
making programs easier to read and to modify.
• Be aware, however, that exception handling
usually requires more time and resources
because it requires instantiating a new
exception object, rolling back the call stack, and
propagating the errors to the calling methods.
64
65