throws與throw
阿新 • • 發佈:2018-12-02
1.throws關鍵字–>作用於方法上
在進行方法定義時,如果要明確告訴呼叫者方法可能產生哪些異常,可以使用throws方法進行宣告,表示將異常拋回給呼叫方,並且當方法出現問題後,可以不進行處理。
public class Test {
public static void main(String[] args) {
try {
System.out.println(calculate(10, 0));
} catch (Exception e) {
e.printStackTrace();
}
}
public static int calculate (int x,int y)throws Exception {//拋給呼叫者
return x/y;
}
}
/*
* java.lang.ArithmeticException: / by zero
* at Test.Test.calculate(Test.java:13)
* at Test.Test.main(Test.java:7)
*/
2.throw關鍵字–>作用於方法中,主要表示手工異常丟擲
public class Test {
public static void main(String[] args) {
try {
throw new Exception ("拋異常");
} catch (Exception e) {
e.printStackTrace();
}
}
}