Java Exception Handling Handling errors using Java’s exception handling mechanism.
Exception Handling
description
Transcript of Exception Handling
[9-1]Programming in Java
Exception Handling
Lecture9
[9-2]Programming in Java
CatchingCatchingexception:exception:
try { … }try { … }
catch { … }catch { … }
ReportingReportingexception:exception:
public boolean myM(int x)public boolean myM(int x)throws AnException {throws AnException {… … throw new AnException();throw new AnException();
}}
finally { … }finally { … }
CreatingCreatingexception:exception:
public class A extends public class A extends Exception {Exception {… …
}}
exception propagationexception propagation
Objectives
[9-3]Programming in Java
The Issue(1)
• Every method should report errors to the caller...
float inverse(double x){ return 1.0/x; }
[9-4]Programming in Java
• Every method should report errors to the caller...
float inverse(double x){ if (x!=0.0) { return 1.0/x;} else { return 0; System.out.println ("Division by zero");}
The Issue(2)
[9-5]Programming in Java
float inverse(double x){ if (x!=0.0) { return 1.0/x;} else { return 0; System.out.println ("Division by zero");}
• Every method should report errors to the caller...
The calling The calling routine needs to routine needs to be informed of be informed of
the error.the error.
The calling The calling routine needs to routine needs to be informed of be informed of
the error.the error.
The Issue(3)
[9-6]Programming in Java
float inverse(double x){ if (x!=0.0) { return 1.0/x;} else { return 0; System.out.println ("Division by zero");}
• Every method should report errors to the caller...
In this case, this In this case, this provides an provides an error error
return.return.
In this case, this In this case, this provides an provides an error error
return.return.
The Issue(4)
[9-7]Programming in Java
Pattern of Exception Handling
P
调用
调用
Q
R
报告
报告
唤醒
唤醒
P
调用
调用
Q
R
报告
报告
报告
唤醒
唤醒
唤醒
[9-8]Programming in Java
• How to Handle
When design methods, design exception class
Allows method an alternative exit path. When error occurs, the method throw an exception object
The code calling the method should catch and handle the thrown exceptions
• Errors are not caught in program(in usual cases)
• RuntimeException happens because of a programming error(“It was your fault”), any other exception occurs because of a bad thing(I/O error,…)
• Exceptions inherit from RuntimeException include such problems as a bad cast, an out-of-bounds, null pointer, ...
• Exception objects and inheritance hierarchy
• Throwable: Error(…), Exception(Runtime, Misc)
Error/exceptions Types
[9-10]Programming in Java
• How to Define? Should be a subclass of Exception(not only Throwabl
e) Exception constructors: Exception(), Exception(String s) May add new fields in the user-defined exception typ
e
• Why to Define?
Exceptions are caught by their types
Add useful data about exceptions
Define Exception Types
[9-11]Programming in Java
class Worker {
public void f1(int val) throws Except1, Except2 { switch (val) { case1: throw new Except1(“Gotcha!”); case2: throw new Except2(“Againnn”); } } }
class Except1 extends Exception {
private String theMessage;
public Except1(String aMsg) {
theMessage = aMsg; }
public String toString() {
return “Except1” + theMessage; }
Example(1)
[9-12]Programming in Java
class Except2 extends Exception {
private String theMessage;
public Except2(String aMsg) {
theMessage = aMsg; }
public String toString() {
return “Except2” + theMessage; }
Example(2)
[9-13]Programming in Java
public class except_example {
public static void main(Sting args[]) { Worker dobj = new Worker(); for (int i = 0; i < 3; i++) { try { dobj.f1(I); System.out.println(“No except,” + i); } catch (Except1 e) { System.out.println(e.toString() + i); } catch (Except2 e) { System.out.println(e.toString() + i); } finally { System.out.println(“Finally code”); } } } }
Example(3)
[9-14]Programming in Java
• System throw an exception automatically All Runtime Exceptions are thrown automatically All Errors are thrown automatically
Throw Exceptions(1)
Public class TestsystemException { public static void main(String args[]) { int a=0, b=5; System.out.println(b/a); }}//throw an ArithmeticException object
[9-15]Programming in Java
• The throw Statement throw <throwable-instance>, throw(return) an exception
Throw Exceptions(2)
int dequeue() throws EmptyQueueException {
int data;
if (isEmpty())
throw (new EmptyQueueException(this));
else { data=m_FirstNode.getData();
m_FirstNode = m_FirstNode.getNext();
return data;}
•Call a method which can throw an exception: readline()
[9-16]Programming in Java
• throws <exception-type-list>
• Specify the types of exceptions that may be thrown in a method (types of exceptions may be returned)
• A method may throw several exception types. If these types are all extended from the same exception type, we can declare the super-exception-type only(not so good)
• RuntimeException and Error are two kinds of exceptions that can be thrown by any method without ‘throw’ clause
• ‘throws’ should be complete and explicit. If there is no ‘throws’, the method can not throw any other exception
The Throws Clause
[9-17]Programming in Java
class ThrowsDemo {
static void procedure() {
System.out.println(“inside procedure”);
throw new IllegalAccessException(“demo”); }
public static void main(String args[]){
procedure();
} }
throws IllegalAccessException {
try {
} catch (IllegalAccessException e) {
System.out.println(“caught” + e) ; }
Example
Inside procedure
Caught java.lang.IllegalAccessException:demo
[9-18]Programming in Java
• try/catch/finally Syntax
try { <try-block> }
catch (exception_type id) { <handler>}
catch (exception_type id) { <handler>}
......
finally { <finally-block> }
• try/catch
Try body is successfully executed or an exception is thrown, exceptions are caught in <try-block>
If any of the code inside <try-block> throws an exception of some class, which is the type or a subtype inside a catch clause, then:
(a) Java skips the remainder of the code in <try-block>
(b) It executes the handler code inside the catch clause
Catch and Handle Exceptions(1)
[9-19]Programming in Java
• If no such ‘catch’, the exception is passed to a outside try
which can deal with it
• There may be several or none ‘catch’ clauses. If none, the
exception is forwarded to the code invoking the method. But
thrown exceptions should be caught
Catch and Handle Exceptions(2)
[9-20]Programming in Java
fee() fie() foe() throws X throws X
try
{ //…
fie();
// … }
catch(X e)
{ //… }
finally
{ //…
}
try
{ //…
foe();
// … }
finally
{ //…
}
//…
throw new X()
// …
X
Example
[9-21]Programming in Java
class SuperException extends Exception { } class SubException extends SuperException { } class BadCatch { public void goodTry() { try { throw new SubException(); } catch (SuperException superRef) { … } catch (SubException subRef) {…// never be reached
} // an INVALID catch ordering } }
• If exceptions are thrown in current ‘catch’ and ‘finally’, the ‘catch’ clauses will not be rechecked. They are passed to the outside
Catch Ordering
• ‘catch’ clauses are checked in order. An error occurs if the super-type is arranged before the sub-type
[9-22]Programming in Java
• Occasionally, catch an exception without addressing the root cause of it in order to do some cleanup, then take your action and again call ‘throw’ to send the exception back up the calling chain
• Example
Graphics g = image.getGraphics();
try{ <code that might throw exceptions>
} catch (MalformedURLException e) { …
g.dispose(); throw e; //even throw new Exception(“”)
} // g is local, should be disposed of
// Note: finalize takes a long time to dispose of g
Re-throwing Exceptions
[9-23]Programming in Java
• Example public boolean searchFor(String file, String word) throws StreamException { Stream input = null; try { input = new Stream(file); while (!input.eof()) if (input.next() == word) return true; return false; // not found
} finally { if (input != null) input.close(); } //The input file will always be closed
• <finally-block> is executed after <try-block>,where an exception is caught or not
•To clean up internal state or free system resources
• To clean up break, continue and return, so there may be no ‘catch’ clauses(avoid goto statements)
Finally
[9-24]Programming in Java
• Exception Handling is not supposed to replace a simple test
Use exceptions for exceptional circumstances only
Example: the following code tries 1000000 times to pop an empty stack
Tips on Using Exceptions(1)
(a) If (!s.empty()) s.pop(); (b) try { //10 times longer than (a)
s.pop(); } catch (EmptyStackException e){ }
[9-25]Programming in Java
• Do not micromanage exceptions Example: wrap the entire task in a try block
istream is; Stack s; (a) for (i=0 ; i<100; i++) { try { n=s.pop(); } catch (EmptyStackException s) {//stack was empty} try { out.writeInt(n); } catch (IOException e) {//problem reading file} }
Tips on Using Exceptions(2)
(b) try { for (i=0 ; i<100; i++) { n=s.pop(); out.writeInt(n);} }
catch (IOException e) {//problem reading file}
catch (EmptyStackException s) {//stack was empty}
• (b) looks much cleaner than (a), and separate normal processing from exception-handling