An exception is an object that represents an error or a condition that prevents execution from proceeding normally
參考 p.456 程式 Listing 13.1 Quotient.java
參考 p.456 程式 Listing 13.2 QuotientWithIf.java
參考 p.457 程式 Listing 13.3 QuotientWithException.java
throw new ArithmeticException("Divisor cannot be zero"); try { 可能發生例外的程式碼 } catch (ArithmeticException ex) { 發生ArithmeticException例外時 } catch (Exception ex) { 發生其他例外時 }
參考 p.459 程式 Listing 13.4 QuotientWithMethod.java
參考 p.460 程式 Listing 13.5 FileNotFoundExceptionDemo.java
參考 p.460 程式 Listing 13.6 InputMismatchExceptionDemo.java
p.461 Figure 13.1 Exceptions thrown are instances of the classes shown in this diagram, or of subclasses of one of these classes
p.462 TABLE 13.1 Examples of Subclasses of Error
class | 可能發生的原因 |
---|---|
LinkageError | Class 的介面更改,無法連結 |
VirtualMachineError | 系統錯誤(記憶體不夠等) |
p.462 TABLE 13.2 Examples of Subclasses of Exception
class | 可能發生的原因 |
---|---|
ClassNotFoundException | Class 找不到 |
IOException | 讀取或寫入資料錯誤 |
p.462 TABLE 13.3 Examples of Subclasses of RuntimeException
class | 可能發生的原因 |
---|---|
ArithmeticException | 計算時錯誤(如除以0) |
NullPointerException | 物件變數沒有 new ,直接存取欄位或方法 |
IndexOutOfBoundsException | 陣列索引超過下限或上限 |
IllegalArgumentException | 傳遞給方法的參數不正確 |
int number = Integer.MAX_VALUE + 1; System.out.println(number);
p.463 Figure 13.2 Exception handling in Java consists of declaring exceptions, throwing exceptions, and catching and processing exceptions
public void myMethod() throws IOException public void myMethod() throws Exception1, Exception2, ..., ExceptionN
throw new IllegalArgumentException("Wrong Argument");
try { statements; // Statements that may throw exceptions } catch (Exception1 exVar1) { handler for exception1; } catch (Exception2 exVar2) { handler for exception2; } catch (ExceptionN exVar3) { handler for exceptionN; }
p.465 Figure 13.3 If an exception is not caught in the current method, it is passed to its caller. The process is repeated until the exception is caught or passed to the main method.
p.466 Note 多個 exception 的 catch 順序
p.466 Note 必須處理的 exception
只要不是 error 或 RuntimeException ,必須自己處理或另外丟給別人處理
p.466 Figure 13.4 Throwable is the root class for all exception objects.
參考 p.467 程式 Listing 13.7 TestException.java
參考 p.468 程式 Listing 13.8 CircleWithException.java
參考 p.468 程式 Listing 13.9 TestCircleWithException.java
finally 句子一定會被執行
參考 p.470 程式 Listing 13.10 FinallyDemo.java
try { System.out.println(refVar.toString()); } catch (NullPointerException ex) { System.out.println("refVar is null"); }
if (refVar != null) System.out.println(refVar.toString()); else System.out.println("refVar is null");
try { statements; } catch (TheException ex) { perform operations before exits; throw ex; }
參考 p.472 程式 Listing 13.11 ChainedExceptionDemo.java
參考 p.473 程式 Listing 13.12 InvalidRadiusException.java