[英]My program is outputting a warning because of IOException?
您如何解決此警告:無法到達的catch子句? 我已經看到人們在FileNotFound之后確實捕獲了IOException,但我不知道這是什么問題。
公共無效run(){
int count = 0;
try {
Scanner scan = new Scanner(new FileInputStream(file));
while(scan.hasNext()) {
scan.next();
count++;
}
} catch(FileNotFoundException exception) {
System.out.println(file + " not found");
} catch(IOException exception) {
exception.printStackTrace();
}
您可以擺脫代碼
} catch(IOException exception) {
exception.printStackTrace();
}
原因是在try
塊中引發的唯一異常是FileNotFoundException
及其IOException
的子類。 為了進一步跟蹤異常,這應該足夠了:
catch(FileNotFoundException exception) {
System.out.println("" + " not found");
exception.printStackTrace();
}
從代碼中拋出的唯一異常(屬於IOException
異常家族)是FileNotFoundException
。 由於您已經有一個(專門的)捕獲塊,因此IOException
捕獲塊變得多余。
在其他情況下,他們可能在try-catch中做了其他事情,這也引發了IOException
系列中的另一個異常(或者可能引發了IOException
本身),因此捕獲IOException
是有意義的。 例如,考慮以下代碼:
FileInputStream fis = new FileInputStream(file);
fis.read();
如果將其包裝在try-catch塊中,則可以同時捕獲FileNotFoundException
和IOException
並且不會出現警告。 第二行直接引發IOException
。
可以看出這里 ,掃描儀吞下任何IOException
秒讀取期間,由底層流拋出。 如果您擔心處理文件讀取問題,則有兩種選擇:
a)不要使用Scanner,而是使用一些較低級別的API,例如Reader或InputStream。
b)一旦您的while
循環完成,請執行此操作(盡管這是非常不常見的事情):
if (scan.ioException() != null) {
throw scan.ioException();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.