【正文】
? Exception() Constructs a new exception with null as its detail message. ? Exception(String message) Constructs a new exception with the specified detail message. ? 自定義異常類可以不定義構(gòu)造方法 ? SimpleException() { super()。 } ? 自定義異常類定義自已的構(gòu)造方法 異常 (Exception) 35 ? 自定義異常 ? 自定義異常類定義自已的構(gòu)造方法 異常 (Exception) class MyException extends Exception { private int x。 public MyException() {} public MyException(String msg) { super(msg)。 } public MyException(String msg, int x) { super(msg)。 = x。 } } class ExtraFeatures { public static void f() throws MyException { (Throws MyException from f())。 throw new MyException()。 } public static void g() throws MyException { (Throws MyException from g())。 throw new MyException(Originated in g())。 } public static void h() throws MyException { (Throws MyException from h())。 throw new MyException(Originated in h(), 47)。 } } try { f()。 } catch(MyException e) { (e)。 } Throwing MyException from f() MyException g()。 MyException f om g() MyException: Originated in g() om h()in h()h()。36 ? Quiz ? Question: Is the following code legal? 異常 (Exception) try { ... } finally { ... } ? Answer: Yes, it39。s legal. A try statement does not have to have a catch statement if it has a finally statement. If the code in the try statement has multiple exit points and no associated catch clauses, the code in the finally statement is executed no matter how the try block is exited. 37 ? Quiz ? Question: What exceptions can be caught by the following handler? 異常 (Exception) catch (Exception e) { ... } ? Answer: This handler catches exceptions of type Exception。 therefore, it catches any exception. This can be a poor implementation because you are losing valuable information about the type of exception being thrown and making your code less efficient. As a result, the runtime system is forced to determine the type of exception before it can decide on the best recovery strategy. 38 ? Quiz ? Question: What exception types can be caught by the following handler? 異常 (Exception) ... } catch (Exception e) { ... } catch (ArithmeticException a) { ... } ? Answer: This first handler catches exceptions of type Exception。 therefore, it catches any exception, including ArithmeticException. The second handler could never be reached. This code will not pile. 第八講 結(jié)束 !