交通大學資訊工程學系 programming in java exception handling again 蔡文能...

28
交交交交交交交交交交 Programming in Java Exception Handling again 蔡蔡蔡 蔡蔡蔡蔡蔡蔡蔡蔡蔡蔡 [email protected] http://www.csie.nctu.edu.tw/~tsaiwn/java /

Post on 20-Dec-2015

259 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: 交通大學資訊工程學系 Programming in Java Exception Handling again 蔡文能 交通大學資訊工程學系 tsaiwn@csie.nctu.edu.tw tsaiwn/java//java

交通大學資訊工程學系

Programming in Java

Exception Handling again

蔡文能交通大學資訊工程學系[email protected]

http://www.csie.nctu.edu.tw/~tsaiwn/java/

Page 2: 交通大學資訊工程學系 Programming in Java Exception Handling again 蔡文能 交通大學資訊工程學系 tsaiwn@csie.nctu.edu.tw tsaiwn/java//java

交通大學資訊工程學系 蔡文能 7-第 2頁

Java More Java Examples

Agenda

Exception handling

Exception handling in Java

Exception handling in C++

Page 3: 交通大學資訊工程學系 Programming in Java Exception Handling again 蔡文能 交通大學資訊工程學系 tsaiwn@csie.nctu.edu.tw tsaiwn/java//java

交通大學資訊工程學系 蔡文能 7-第 3頁

Java More Java Examples

Exception? An exceptionexception is any unusual event, either erroneous or

not, detectable by either hardware or software, that may require special processing

Without exception handlingexception handling When an exception occurs, control goes to the operating system,

where typically an error message is displayed

the program is terminated

With exception handling Programs are allowed to trap exceptions There is a possibility to fix the problem and continuing execution

Page 4: 交通大學資訊工程學系 Programming in Java Exception Handling again 蔡文能 交通大學資訊工程學系 tsaiwn@csie.nctu.edu.tw tsaiwn/java//java

交通大學資訊工程學系 蔡文能 7-第 4頁

Java More Java Examples

What to do when Exception occurs?There are several ways a function may react when encountering an unexpected/erroneous situation (i.e., Exception ) Terminate the programTerminate the program

Cannot be used in a program that cannot afford to crash Return a value representing “error”Return a value representing “error”

Raise a flagRaise a flagMany standard C library functions used global variable errno

Need to check the flag after every operation Losses information

Call a function supplied to be called in case of errorCall a function supplied to be called in case of errorRaise a signal / EventHow will it handle the error?

char* String::getString(); //ok: return NUKK on errorint atoi(const char *); //what to return for “bad-str”?

Page 5: 交通大學資訊工程學系 Programming in Java Exception Handling again 蔡文能 交通大學資訊工程學系 tsaiwn@csie.nctu.edu.tw tsaiwn/java//java

交通大學資訊工程學系 蔡文能 7-第 5頁

Java More Java Examples

When To Use Exceptions

Required by compiler when using some statements (Java)

Make code safer (catch fatal errors)

Fix the problem and try again

Patch the problem and continue

Make a complex error mechanism simpler

Page 6: 交通大學資訊工程學系 Programming in Java Exception Handling again 蔡文能 交通大學資訊工程學系 tsaiwn@csie.nctu.edu.tw tsaiwn/java//java

交通大學資訊工程學系 蔡文能 7-第 6頁

Java More Java Examples

Exception example

try {

readFromFile("datafile");

} catch (FileNotFoundException e) {

System.err.println("Error: File not found");

}

try {

readFromFile("datafile");

} catch (FileNotFoundException e) {

System.err.println("Error: File not found");

}

Page 7: 交通大學資訊工程學系 Programming in Java Exception Handling again 蔡文能 交通大學資訊工程學系 tsaiwn@csie.nctu.edu.tw tsaiwn/java//java

交通大學資訊工程學系 蔡文能 7-第 7頁

Java More Java Examples

Exception Handling: Some Options

Print something

Throw a new exception

Re-Throw the exception

Fix the problem

Exit

Page 8: 交通大學資訊工程學系 Programming in Java Exception Handling again 蔡文能 交通大學資訊工程學系 tsaiwn@csie.nctu.edu.tw tsaiwn/java//java

交通大學資訊工程學系 蔡文能 7-第 8頁

Java More Java Examples

Exception Handling: Printing

You can print a stack trace by calling the exception method printStackTrace()

Sometimes it's better to send error messages to stderr: System.err.println("Error: invalid thingy");

Some applications log error messages file logging service (syslog).

Page 9: 交通大學資訊工程學系 Programming in Java Exception Handling again 蔡文能 交通大學資訊工程學系 tsaiwn@csie.nctu.edu.tw tsaiwn/java//java

交通大學資訊工程學系 蔡文能 7-第 9頁

Java More Java Examples

Throwing Objects

Why throw an object? Additional data encapsulated

An object is created upon invoking the throw statement

Can be created with additional data, passed to Ctor

Object is destroyed after the catch clause ends

Page 10: 交通大學資訊工程學系 Programming in Java Exception Handling again 蔡文能 交通大學資訊工程學系 tsaiwn@csie.nctu.edu.tw tsaiwn/java//java

交通大學資訊工程學系 蔡文能 7-第 10頁

Java More Java Examples

Exception Handling: throw

• You can throw an exception (object) from an exception handler (a catch block).• Allows you to change exception type and/or

error message.• You can also alter the base of the stack trace

•fillInStackTrace()

Page 11: 交通大學資訊工程學系 Programming in Java Exception Handling again 蔡文能 交通大學資訊工程學系 tsaiwn@csie.nctu.edu.tw tsaiwn/java//java

交通大學資訊工程學系 蔡文能 7-第 11頁

Java More Java Examples

Exception Handling: Re-throw

• You can throw an exception from an exception handler (a catch block) without changing anything:• called rethrowing• The caller needs to deal with the exception.• This also happens if you don't catch the

exception!• sometimes you need to take some action and

then rethrow the exception.

Page 12: 交通大學資訊工程學系 Programming in Java Exception Handling again 蔡文能 交通大學資訊工程學系 tsaiwn@csie.nctu.edu.tw tsaiwn/java//java

交通大學資訊工程學系 蔡文能 7-第 12頁

Java More Java Examples

Another way to re-throw

You can allow selected types of exceptions to be propogated to the caller of your method:

void blah() throws IOException {

Within blah() you don't need to catch these exceptions (to be able to compile).

Page 13: 交通大學資訊工程學系 Programming in Java Exception Handling again 蔡文能 交通大學資訊工程學系 tsaiwn@csie.nctu.edu.tw tsaiwn/java//java

交通大學資訊工程學系 蔡文能 7-第 13頁

Java More Java Examples

Exception examplepublic class ThrowUp {

public static void main(String[ ] args) { String tmp; try { // generate an ArrayIndexOutOfBoundsExceptions ..

// .. (on purpose!). for (int i=0 ; i<args.length+10 ; i++) { tmp = args[i]; } System.out.println("I made it!"); } catch (ArrayIndexOutOfBoundsException up) { throw new SecurityException("Trouble"); } } // main}

Page 14: 交通大學資訊工程學系 Programming in Java Exception Handling again 蔡文能 交通大學資訊工程學系 tsaiwn@csie.nctu.edu.tw tsaiwn/java//java

交通大學資訊工程學系 蔡文能 7-第 14頁

Java More Java Examples

Exception Handling: Fix the problem.

• You can't fix things and then resume execution automatically• you can do this in C++.

• You can have a loop the retries the code again.

Page 15: 交通大學資訊工程學系 Programming in Java Exception Handling again 蔡文能 交通大學資訊工程學系 tsaiwn@csie.nctu.edu.tw tsaiwn/java//java

交通大學資訊工程學系 蔡文能 7-第 15頁

Java More Java Examples

Exception Handling: exiting

• Sometimes the error is fatal, and you want to stop the program immediately.

System.exit();

Page 16: 交通大學資訊工程學系 Programming in Java Exception Handling again 蔡文能 交通大學資訊工程學系 tsaiwn@csie.nctu.edu.tw tsaiwn/java//java

交通大學資訊工程學系 蔡文能 7-第 16頁

Java More Java ExamplesWait.java

public class Wait { public static void main(String[ ] args) { boolean done=false; int seconds=0; try { seconds = Integer.parseInt(args[0]); } catch (Exception e) { System.out.println("Please specify the number of seconds"); System.exit(1); } long initialtime = System.currentTimeMillis( ); while (!done) { try { if (System.currentTimeMillis()-initialtime < seconds*1000) throw new Exception("Not Yet - keep trying"); done=true; } catch (Exception e) { System.out.println(e); } } System.out.println("Done!\n"); }}

Page 17: 交通大學資訊工程學系 Programming in Java Exception Handling again 蔡文能 交通大學資訊工程學系 tsaiwn@csie.nctu.edu.tw tsaiwn/java//java

交通大學資訊工程學系 蔡文能 7-第 17頁

Java More Java Examples

How/when do you generate exceptions?

Use throw:

throw new Exception("broken!");

You can use throw anywhere. you detect some error that means the following code should not be executed.

In some cases, you can think of throw as a alternate return

Page 18: 交通大學資訊工程學系 Programming in Java Exception Handling again 蔡文能 交通大學資訊工程學系 tsaiwn@csie.nctu.edu.tw tsaiwn/java//java

交通大學資訊工程學系 蔡文能 7-第 18頁

Java More Java Examples

Exception Enforcement

In general, you do the following: specify what exceptions each method can generate. write code to catch all exceptions that can be generated by a

method call.

The compiler (usually) enforces this it is a compilation error to call a method without catching it's

declared exception types.

Page 19: 交通大學資訊工程學系 Programming in Java Exception Handling again 蔡文能 交通大學資訊工程學系 tsaiwn@csie.nctu.edu.tw tsaiwn/java//java

交通大學資訊工程學系 蔡文能 7-第 19頁

Java More Java Examples

RunTime Exceptions

There are exceptions that are generated by the system (that are usually caused by programming mistakes): NullPointerException (null references) ArrayIndexOutOfBoundsException

If you don't catch these, a stack trace will be generated and the program will terminate.

The compiler does not force you to catch these exceptions.

Page 20: 交通大學資訊工程學系 Programming in Java Exception Handling again 蔡文能 交通大學資訊工程學系 tsaiwn@csie.nctu.edu.tw tsaiwn/java//java

交通大學資訊工程學系 蔡文能 7-第 20頁

Java More Java Examples

Exception Types

Exceptions are objects!

Exception types are classes. A (quite large!) hierarchy of classes.

All exception types are derived from the class Exception there are some methods defined in this base class.

Page 21: 交通大學資訊工程學系 Programming in Java Exception Handling again 蔡文能 交通大學資訊工程學系 tsaiwn@csie.nctu.edu.tw tsaiwn/java//java

交通大學資訊工程學系 蔡文能 7-第 21頁

Java More Java Examples

NullPointer.javaimport java.util.*;public class NullPointer { public static void main(String[ ] args) { Date f = new Date(); f=null; PrintSomething2(f); // comment out to test PrintSomething PrintSomething(f); } // no checks, if x is null runtime exception default behavior static void PrintSomething(Object x) { System.out.println(x.getClass( ).getName()); } // we explicitly check for runtime exception! static void PrintSomething2(Object x) { try { System.out.println(x.getClass().getName()); } catch (RuntimeException re) { System.out.println("Fatal Error!"); System.exit(1); } } // main}

Page 22: 交通大學資訊工程學系 Programming in Java Exception Handling again 蔡文能 交通大學資訊工程學系 tsaiwn@csie.nctu.edu.tw tsaiwn/java//java

交通大學資訊工程學系 蔡文能 7-第 22頁

Java More Java Examples

ThrowableThrowable

ExceptionException ErrorError

RunTimeExceptionRunTimeException

NullPointerExceptionNullPointerException

ArithmeticExceptionArithmeticException

IOExceptionIOException

Exception Type Hierarchy (partial)

EOFExceptionEOFException

VirtualMachineErrorVirtualMachineError

Page 23: 交通大學資訊工程學系 Programming in Java Exception Handling again 蔡文能 交通大學資訊工程學系 tsaiwn@csie.nctu.edu.tw tsaiwn/java//java

交通大學資訊工程學系 蔡文能 7-第 23頁

Java More Java Examples

Some Exception Methods

These are actually inherited from throwable

printStackTrace()

fillInStackTrack()

getMessage()

Page 24: 交通大學資訊工程學系 Programming in Java Exception Handling again 蔡文能 交通大學資訊工程學系 tsaiwn@csie.nctu.edu.tw tsaiwn/java//java

交通大學資訊工程學系 蔡文能 7-第 24頁

Java More Java Examples

Creating Your Own Exception Types

It is often useful to create your own type of exception. generally all you create is a name. you can get fancy and add new methods to your exception

class(es).

Page 25: 交通大學資訊工程學系 Programming in Java Exception Handling again 蔡文能 交通大學資訊工程學系 tsaiwn@csie.nctu.edu.tw tsaiwn/java//java

交通大學資訊工程學系 蔡文能 7-第 25頁

Java More Java Examples

User-defined Exception Type

class FooException extends Exception {}

// ..

class BlahException extends Exception {

BlahException(){}

BlahException(String s) { super(s); }

}

// ..

throw new BlahException("Invalid blah");

Page 26: 交通大學資訊工程學系 Programming in Java Exception Handling again 蔡文能 交通大學資訊工程學系 tsaiwn@csie.nctu.edu.tw tsaiwn/java//java

交通大學資訊工程學系 蔡文能 7-第 26頁

Java More Java Examples

using finally

try { statements . . .} catch (ExceptionType1 ename1) { error handling statements . . .} catch (ExceptionType2 ename2) { error handling statements . . .} finally { … this code always executed …}

Page 27: 交通大學資訊工程學系 Programming in Java Exception Handling again 蔡文能 交通大學資訊工程學系 tsaiwn@csie.nctu.edu.tw tsaiwn/java//java

交通大學資訊工程學系 蔡文能 7-第 27頁

Java More Java Examples

Why finally?

What is there to clean up? No memory cleanup required in Java! No destructors to call!

Sometimes you need to set the state of things (fields) to some stable (acceptable) state.

Page 28: 交通大學資訊工程學系 Programming in Java Exception Handling again 蔡文能 交通大學資訊工程學系 tsaiwn@csie.nctu.edu.tw tsaiwn/java//java

交通大學資訊工程學系 蔡文能 7-第 28頁

Java More Java Examples

Exception Handling again

謝謝捧場http://www.csie.nctu.edu.tw/~tsaiwn/java/

蔡文能