throw:
- 表示方法內拋出某種異常對象
- 如果異常對象是非 RuntimeException 則需要在方法申明時加上該異常的拋出 即需要加上 throws 語句 或者 在方法體內 try catch 處理該異常,否則編譯報錯
- 執行到 throw 語句則后面的語句塊不再執行
throws:
- 方法的定義上使用 throws 表示這個方法可能拋出某種異常
- 需要由方法的調用者進行異常處理
package constxiong.interview; import java.io.IOException; public class TestThrowsThrow { public static void main(String[] args) { testThrows(); Integer i = null; testThrow(i); String filePath = null; try { testThrow(filePath); } catch (IOException e) { e.printStackTrace(); } } /** * 測試 throws 關鍵字 * @throws NullPointerException */ public static void testThrows() throws NullPointerException { Integer i = null; System.out.println(i + 1); } /** * 測試 throw 關鍵字拋出 運行時異常 * @param i */ public static void testThrow(Integer i) { if (i == null) { throw new NullPointerException();//運行時異常不需要在方法上申明 } } /** * 測試 throw 關鍵字拋出 非運行時異常,需要方法體需要加 throws 異常拋出申明 * @param i */ public static void testThrow(String filePath) throws IOException { if (filePath == null) { throw new IOException();//運行時異常不需要在方法上申明 } } }
來一道刷了進BAT的面試題?