![](/img/trans.png)
[英]Why we don't have to add try-catch to a RuntimeException?
[英]Why is it that we don't need to use try-catch block when reading data but we do need try-catch when attaching a Scanner to a file?
我正在閱讀《掃描儀》上的一本編程書,這就是說,由於捕獲了IOException,因此在讀取數據時不需要使用try-catch塊,但是在將掃描儀附加到文件時,我們需要使用try-catch。
例如,在以下代碼中,try-catch是必需的。 您能給我看一個不需要try-catch但錯誤被IOException捕獲的示例嗎?
Scanner scnaFile = null;
String fileName = "dataFile.txt";
try{
scanFile = new Scanner(new File(fileName));
} catch (FileNotFoundException ex){
System.err.println(filename + " not found");
System.exit(1);
}
您能給我看一個不需要try-catch但錯誤被IOException捕獲的示例嗎?
例:
Scanner sc = new Scanner(new File("myNumbers"));
while (sc.hasNextLong()) {
long aLong = sc.nextLong();
}
這些nextXXX
方法不會引發任何與I / O相關的異常,因為這是在代碼中捕獲的。
但是,如果輸入被取消,它們將引發異常。
閱讀掃描儀Javadoc
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.