Java- 受檢的異常(checked Exception)
阿新 • • 發佈:2019-01-27
受檢的異常
- Exception分為兩種
RuntimeException
及其子類,可以不明確處理,例如邊界異常,解析整型時格式異常。- 否則,稱為受檢的異常(checked Exception),更好的保護安全性
受檢的異常,要求明確進行語法處理
- 要麼捕獲(catch)
- 要麼丟擲(throw):在方法的簽名後面用
throws xxx
來宣告
- 在子類中,如果要覆蓋父類的一個方法,若父類中的方法聲明瞭throws異常,則子類的方法也可以throws異常
- 可以丟擲子類異常(更具體的異常),但不能丟擲更一般的異常
public class ExceptionTrowsToOther{ public
try…with…resource
try(型別 變數名=new型別() ){
...
}
自動添加了finally{ 變數.close(); }
對可關閉的資源進行關閉操作
static String ReadOneLine1(String path){
BufferedReader br=null;
try {
br=new BufferedReader(new FileReader(path));
return br.readLine();
} catch(IOException e) {
e.printStackTrace();
} finally {
if(br!=null){
try{
br.close();
}catch(IOException ex){
}
}
}
return null;
}
static String ReadOneLine2(String path)
throws IOException
{
try(BufferedReader br= new BufferedReader(new FileReader(path))){
return br.readLine();
}
}
上面兩個函式ReadOneLine1及ReadOneLine2效果相同。