throwとthrowsの違いは?


throwとthrowsの違いは?
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();//              
    		}
    	}
    }
    

     
    【Java面接問題と回答】整理推薦
  • 基礎と文法
  • 集合
  • ネットワークプログラミング
  • 同時プログラミング
  • Web
  • 安全
  • 設計モード
  • フレーム
  • アルゴリズムとデータ構造
  • 異常
  • ファイル解析と生成
  • Linux
  • MySQL
  • Oracle
  • Redis
  • Dubbo