java遺珠之多異常
阿新 • • 發佈:2019-02-09
catch可以同時捕獲多個異常,示例如下:
public void writeList() {
// The FileWriter constructor throws IOException, which must be caught.
PrintWriter out = null;
try {
System.out.println("Entered try statement");
out = new PrintWriter(new FileWriter("OutFile.txt"));
for (int i = 0; i < SIZE; i++) {
// The get(int) method throws IndexOutOfBoundsException, which must be caught.
out.println("Value at: " + i + " = " + list.get(i));
}
out.close();
} catch (IOException | IndexOutOfBoundsException e) {
//ERROR e=new IOException("new io exception");
e.printStackTrace();
}
}
但要注意的是如果是捕獲多異常的話,異常變數預設就會變成final的了,不能再進行賦值。
單個異常不是final的
catch (IOException e) {
e=new IOException("new io exception");
e.printStackTrace();
}