Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 8 Error Handing with Exceptions. 集美大学 计算机工程学院 Java 程序设计 2008-2009 What really matters is what happens after the error occurs. How is the error.

Similar presentations


Presentation on theme: "Chapter 8 Error Handing with Exceptions. 集美大学 计算机工程学院 Java 程序设计 2008-2009 What really matters is what happens after the error occurs. How is the error."— Presentation transcript:

1 Chapter 8 Error Handing with Exceptions

2 集美大学 计算机工程学院 Java 程序设计 2008-2009 What really matters is what happens after the error occurs. How is the error handled? Who handles it? Can the program recover, or should it just die? A golden rule of programming ----- Errors occur in software programs.

3 集美大学 计算机工程学院 Java 程序设计 2008-2009 Exception ● Exceptions to provide error-handling capabilities Exceptions handle unexpected situations: ▼ file not found, network failure, illegal argument ● An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.

4 集美大学 计算机工程学院 Java 程序设计 2008-2009 By using exceptions to manage errors, Java programs have the following advantages over traditional error management techniques: 1:Separating Error Handing Code from “Regular” Code 2:Propagating Errors Up the Call Stack 3:Grouping Error Types and Error Differentiation

5 集美大学 计算机工程学院 Java 程序设计 2008-2009

6 集美大学 计算机工程学院 Java 程序设计 2008-2009 // TestException.java // 正常运行 public class TestException { public static void main(String[] args) { int a, b; a = 6; b = 1; // 除数 b 的值不为 0 System.out.println( a / b ); } Result : 6 Example1: / by zero

7 集美大学 计算机工程学院 Java 程序设计 2008-2009 // 除数 b 的值为 0 , TestException.java 程序异常终止 public class TestException { public static void main(String[] args) { int a, b; a = 6; b = 0; // 除数 b 的值为 0 System.out.println( a / b ); } Result : Exception in thread "main“ java.lang.ArithmeticException: / by zero at TestException.main(TestException.java:6)

8 集美大学 计算机工程学院 Java 程序设计 2008-2009 // 除数 b 为 0 ,引入异常处理机制 public class TestException { public static void main(String[] args) { int a = 6; int b = 0; try { System.out.println("a/b 的值是: " + a/b); } catch (ArithmeticException e) { System.out.println(" 程序出现异常,变量 b 不能为 0 。 "); } System.out.println(" 程序正常结束。 "); } Result : 程序出现异常,变量 b 不能为 0 。 程序正常结束。

9 集美大学 计算机工程学院 Java 程序设计 2008-2009 throwing an exception: creating an exception object and handing it to the runtime system ● Many kinds of errors can cause exceptions ▲ serious hardware errors ▲ simple programming errors ● When such an error occurs within a Java method, the method creates an exception object and hands it off to the runtime system. ● The exception object contains information about the exception, including its type and the state of the program when the error occurred. ● The runtime system is then responsible for finding some code to handle the error. In Java terminology

10 集美大学 计算机工程学院 Java 程序设计 2008-2009 catch the exception : The exception handler chosen is said to catch the exception. ● After a method throws an exception, the runtime system leaps into action to find someone to handle the exception. ● The set of possible "someones" to handle the exception is the set of methods in the call stack of the method where the error occurred. ● The runtime system searches backwards through the call stack, beginning with the method in which the error occurred, until it finds a method that contains an appropriate exception handler. ● An appropriate handler is found and one of the calling methods handles the exception. * An exception handler is considered appropriate if the type of the exception thrown is the same as the type of exception handled by the handler. In Java terminology

11 集美大学 计算机工程学院 Java 程序设计 2008-2009 If the runtime system exhaustively searches all of the methods on the call stack without finding an appropriate exception handler, the runtime system (and consequently the Java program) terminates.

12 集美大学 计算机工程学院 Java 程序设计 2008-2009 Java's Catch or Specify Requirement Java requires that a method either catch or specify all checked exceptions that can be thrown within the scope of the method. Catch:A method can catch an exception by providing an exception handler for that type of exception. Specify:If a method chooses not to catch an exception, the method must specify that it can throw that exception.

13 集美大学 计算机工程学院 Java 程序设计 2008-2009 try { // code that might throw a particular exception } catch (MyExceptionType myExcept) { // code to execute if a MyExceptionType exception is thrown } catch (Exception otherExcept) { // code to execute if a general Exception exception is thrown } Catching and Handling Exceptions the try block & the catch block (s)

14 集美大学 计算机工程学院 Java 程序设计 2008-2009 // 数组下标越界异常 public class TestException{ public static void main(String[] args) { int[] intArray = new int[3]; try { for (int i=0;i<=intArray.length; i++) { intArray[i] = i ; System.out.println("intArray[" + i + "] = " + intArray[i]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("intArray 数组下标越界异常。 "); } catch (ArithmeticException e) { System.out.println(" 除数为 0 异常。 "); } System.out.println(" 程序正常结束。 "); } Example 2:

15 集美大学 计算机工程学院 Java 程序设计 2008-2009 Result : ---------- java ---------- intArray[0] = 0 intArray[1] = 1 intArray[2] = 2 intArray 数组下标越界异常。 程序正常结束。 Normal Termination Output completed (0 sec consumed ).

16 集美大学 计算机工程学院 Java 程序设计 2008-2009 // 数组下标越界异常和除数为 0 异常 public class TestException { public static void main(String[] args) { int[] intArray = new int[3]; try { for (int i=0;i<=intArray.length; i++) { intArray[i] = i ; System.out.println("intArray[" + i + "] = " + intArray[i]); System.out.println("intArray[" + i + "] 模 "+ (i-2)+" 的值 : "+ intArray[i]%(i-2)); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("intArray 数组下标越界异常。 "); } catch (ArithmeticException e) { System.out.println(" 除数为 0 异常。 "); } System.out.println(" 程序正常结束。 "); } Example3:

17 集美大学 计算机工程学院 Java 程序设计 2008-2009 Result : ---------- java ---------- intArray[0] = 0 intArray[0] 模 -2 的值 : 0 intArray[1] = 1 intArray[1] 模 -1 的值 : 0 intArray[2] = 2 除数为 0 异常。 程序正常结束。 Normal Termination Output completed (0 sec consumed ).

18 集美大学 计算机工程学院 Java 程序设计 2008-2009 try 、 catch & finally try { //block of code to monitor for errors throw ExceptionType;//throw an exception } catch (ExceptionType1 e) { //exception handler for ExceptionType1 } catch (ExceptionType2 e) { //exception handler for ExceptionType2 } finally { //block of code to be executed before try block ends }

19 集美大学 计算机工程学院 Java 程序设计 2008-2009 public class TestException{ public static void main (String args[]) { int i = 0; String greetings [] = { " Hello world !", " Hello World !! ", " HELLO WORLD !!!" }; while (i < 4) { try { // 特别注意循环控制变量 i 的设计,避免造成无限循环 System.out.println (greetings[i++]); } catch (ArrayIndexOutOfBoundsException e){ System.out.println(" 数组下标越界异常 "); } finally { System.out.println("-------------------------- "); }

20 集美大学 计算机工程学院 Java 程序设计 2008-2009 Result : ---------- java ---------- Hello world ! -------------------------- Hello World !! -------------------------- HELLO WORLD !!! -------------------------- 数组下标越界异常 -------------------------- Normal Termination Output completed (0 sec consumed).

21 集美大学 计算机工程学院 Java 程序设计 2008-2009 The throw Statement ● Before you can catch an exception, some Java code somewhere must throw one. ● Any Java code can throw an exception ▲ your code ▲ code from a package written by someone else (such as the packages that come with the Java development environment) ▲ or the Java runtime system. ● Regardless of who (or what) throws the exception, it's always thrown with the Java throw statement.

22 集美大学 计算机工程学院 Java 程序设计 2008-2009 The throw Statement : throw someThrowableObject; ● All Java methods use the throw statement to throw an exception. ● The throw statement requires a single argument: a throwable object. ● In the Java system, throwable objects are instances of any subclass of the Throwable class. ● If you attempt to throw an object that is not throwable, the compiler refuses to compile your program and displays an error message

23 集美大学 计算机工程学院 Java 程序设计 2008-2009 // 创建自定义异常类 MyException class MyException extends Exception{ int pass; MyException(int x){ pass = x; } //throw 抛出并处理自定义异常 class TestMyException{ public static void main(String[] args){ try{ for (int i=0;i<10 ;i++ ){ if (i == 4) throw new MyException(i); System.out.println("pass #" + i + "\n"); } catch(MyException e){ System.out.println("Exception on pass #" + e.pass); }

24 集美大学 计算机工程学院 Java 程序设计 2008-2009 TestMyException.java Result : ---------- java ---------- pass #0 pass #1 pass #2 pass #3 Exception on pass #4 Normal Termination Output completed (0 sec consumed). ★ Remember :you can throw only objects that inherit from the java.lang.Throwable class.

25 集美大学 计算机工程学院 Java 程序设计 2008-2009 // 除数 b 为 0 ,引入异常处理机制 public class TestException { public static void main(String[] args) { int a = 6; int b = 0; try { if (b == 0) throw new ArithmeticException(); System.out.println("a/b 的值是: " + a/b); } catch (ArithmeticException e) { System.out.println(" 程序出现异常,变量 b 不能为 0 。 "); } System.out.println(" 程序正常结束。 "); } Example1 again:

26 集美大学 计算机工程学院 Java 程序设计 2008-2009 The previous section showed you how to write an exception handler for the method in the class. ● Sometimes ----- catch Sometimes, it's appropriate for your code to catch exceptions that can occur within it. ● In other cases ----- thrown by method In other cases, however, it's better to let a method further up the call stack handle the exception. Specifying the Exceptions Thrown by a Method

27 集美大学 计算机工程学院 Java 程序设计 2008-2009 The throws Clause: throws EmptyStackException ● The throws clause specifies that the method can throw an Exception. ● the Java language requires that methods either catch or specify all checked exceptions that can be thrown within the scope of that method. ● You do this with the throws clause of the method declaration.

28 集美大学 计算机工程学院 Java 程序设计 2008-2009 class MyException extends Exception { public MyException() {} public MyException(String msg) { super(msg); } public class TestMyException { int minus(int a, int b) throws MyException { if (a > 2000) throw new MyException(" 参数 a 值超过 2000"); return a/b; } Throws ----- by a method

29 集美大学 计算机工程学院 Java 程序设计 2008-2009 public static void main(String[] args) { TestMyException aDemo = new TestMyException(); int a, b, c; a = 5000; b = 27; try { c = aDemo.minus(a, b); System.out.println(a + " 除以 " + b + " 的值 :" + c); } catch (ArithmeticException e) { System.out.println(" 程序出现算术异常 "); } catch (MyException e) { System.out.println(" 程序出现自定义异常 MyException"); System.out.println(e.getMessage()); } finally { System.out.println(" 程序正常结束 "); }

30 集美大学 计算机工程学院 Java 程序设计 2008-2009 class MyException extends Exception { public MyException() {} public MyException(String msg) { super(msg); } public class TestMyException { int minus(int a, int b) throws MyException { if (a > 2000) throw new MyException(" 参数 a 值超过 2000"); return a/b; } Exception chaining:

31 集美大学 计算机工程学院 Java 程序设计 2008-2009 public static void main(String[] args) { TestMyException aDemo = new TestMyException(); int a, b, c; a = 500; b = 0; try { c = aDemo.minus(a, b); System.out.println(a + " 除以 " + b + " 的值 :" + c); } catch (ArithmeticException e) { System.out.println(" 程序出现算术异常 "); } catch (MyException e) { System.out.println(" 程序出现自定义异常 MyException"); System.out.println(e.getMessage()); } finally { System.out.println(" 程序正常结束 "); }

32 集美大学 计算机工程学院 Java 程序设计 2008-2009 The Throwable Class and Its Subclasses ● you can throw only objects that derive from the Throwable class. This includes direct descendants as well as indirect descendants.

33 集美大学 计算机工程学院 Java 程序设计 2008-2009 Errors: ● When a dynamic linking failure or some other "hard" failure in the virtual machine occurs, the virtual machine throws an Error. ● Typical Java programs should not catch Errors. ● In addition, it's unlikely that typical Java programs will ever throw Errors either.

34 集美大学 计算机工程学院 Java 程序设计 2008-2009 Exceptions: ● Most programs throw and catch objects that derive from the Exception class. ● Exceptions indicate that a problem occurred but that the problem is not a serious systemic problem. ● Most programs you write will throw and catch Exceptions. ● The Exception class has many descendants defined in the Java packages. These descendants indicate various types of exceptions that can occur. For example : ▲ IllegalAccessException - a particular method could not be found. ▲ NegativeArraySizeException - a program attempted to create an array with a negative size.

35 集美大学 计算机工程学院 Java 程序设计 2008-2009 Runtime Exceptions: ● The RuntimeException class represents exceptions that occur within the Java virtual machine (during runtime). ▲ An example : NullPointerException, which occurs when a method tries to access a member of an object through a null reference. ▲ A NullPointerException can occur anywhere a program tries to dereference a reference to an object. ● The cost of checking for the exception often outweighs the benefit of catching it. ▲ Because runtime exceptions are so ubiquitous and attempting to catch or specify all of them all the time would be a fruitless exercise (and a fruitful source of unreadable and unmaintainable code), ● the compiler allows runtime exceptions to go uncaught and unspecified. Runtime Exceptions

36 集美大学 计算机工程学院 Java 程序设计 2008-2009 The Java packages define several RuntimeException classes ● You can catch these exceptions just like other exceptions. ● However, a method is not required to specify that it throws RuntimeExceptions. ● In addition, you can create your own RuntimeException subclasses.

37 集美大学 计算机工程学院 Java 程序设计 2008-2009 public class TestException { public static void main(String[] args) { int a, b; a = 6; b = 0; System.out.println( a / b ); } javac : ---------- javac ---------- Normal Termination Output completed (0 sec consumed). Java: Exception in thread "main“ java.lang.ArithmeticE xception: / by zero at TestException.main(TestExcep tion.java:6) Example1 again:

38 集美大学 计算机工程学院 Java 程序设计 2008-2009 ★ Java requires that a method either catch or specify all Checked exceptions that can be thrown within the scope of the method. ★ the compiler does not require that you catch or specify runtime exceptions. (A method is not required to specify that it throws RuntimeExceptions.) (A method is not required to specify that it throws RuntimeExceptions.) Java's Specify Requirement

39 集美大学 计算机工程学院 Java 程序设计 2008-2009 ● Java has different types of exceptions, including I/O Exceptions, runtime exceptions, and exceptions of your own creation, to name a few. ● Runtime exceptions are those exceptions that occur within the Java runtime system. ● Checked exceptions are exceptions that are not runtime exceptions and are checked by the compiler; the compiler checks that these exceptions are caught or specified. Checked Exceptions

40 集美大学 计算机工程学院 Java 程序设计 2008-2009 Checked exceptions represent useful information about the operation of a legally specified request that the caller may have had no control over and that the caller needs to be informed about--for example, the file system is now full, or the remote end has closed the connection, or the access privileges don't allow this action.

41 集美大学 计算机工程学院 Java 程序设计 2008-2009

42 集美大学 计算机工程学院 Java 程序设计 2008-2009

43 集美大学 计算机工程学院 Java 程序设计 2008-2009 The Handle or Declare Rule: ● Handle the exception by using the try-catch-finally block ● Declare that the code causes an exception by using the throw clause ● Declare exception or exceptions a method can throw: void trouble() throws IOException{} void trouble() throws IOException,OtherExceptiom{} ● You do not need to handle or declare runtime exception or errors.

44 集美大学 计算机工程学院 Java 程序设计 2008-2009

45 集美大学 计算机工程学院 Java 程序设计 2008-2009 Method overriding and Exceptions Example:

46 集美大学 计算机工程学院 Java 程序设计 2008-2009 First ----- throw throw ----- throw ----- throws ----- RuntimeException Second ----- catch catch ----- try ----- catch Rules for you:


Download ppt "Chapter 8 Error Handing with Exceptions. 集美大学 计算机工程学院 Java 程序设计 2008-2009 What really matters is what happens after the error occurs. How is the error."

Similar presentations


Ads by Google