1. 程式人生 > >throws和throw

throws和throw

一、throws

  1. throws 關鍵字將逗號分隔的 java.lang.Throwables 列表作為引數。
  2. 引發非 RuntimeException 異常的任何方法還必須在方法宣告中使用 throws 修飾符來宣告它引發的異常。
  3. 要在 try-catch 塊中包含帶 throws 子句的方法的呼叫,必須提供該方法的呼叫者。
  4. -示例-
    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

  1. throw 關鍵字用於引發異常。
  2. throw 語句將 java.lang.Throwable 作為引數。Throwable 在呼叫棧中向上傳播,直到被適當的 catch 塊捕獲。
  3. -示例-
    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的區別

  1. throws使用在函式上。throws後面跟的異常類,可以跟多個,用逗號隔開。
  2. throw使用在函式內。throw後跟的是異常物件。