throws和throw
阿新 • • 發佈:2018-12-08
一、throws
- throws 關鍵字將逗號分隔的 java.lang.Throwables 列表作為引數。
- 引發非 RuntimeException 異常的任何方法還必須在方法宣告中使用 throws 修飾符來宣告它引發的異常。
- 要在 try-catch 塊中包含帶 throws 子句的方法的呼叫,必須提供該方法的呼叫者。
- -示例-
import java.io.IOException; public class MyClass{ public method readFile(String filename) throws IOException,ClassCastException{ <statements> if (error){ throw new IOException("error reading file"); } } }
二、 throw
- throw 關鍵字用於引發異常。
- throw 語句將 java.lang.Throwable 作為引數。Throwable 在呼叫棧中向上傳播,直到被適當的 catch 塊捕獲。
- -示例-
import java.io.IOException; public class MyClass{ public method readFile(String filename) throws IOException{ <statements> if (error){ throw new IOException("error reading file"); } } }
三、throws和throw的區別
- throws使用在函式上。throws後面跟的異常類,可以跟多個,用逗號隔開。
- throw使用在函式內。throw後跟的是異常物件。