[英]Custom Checked Exception Java
我試圖了解異常,並且在嘗試實現自己制作的自定義代碼時遇到錯誤。 我被指示要制作一個no構造函數,該構造函數將下面的字符串傳遞給super構造函數。 我一直收到編譯器錯誤,但不確定如何解決。 自定義文件如下所示
import java.io.*;
public class UnknownRegionException extends FileNotFoundException {
public UnknownRegionException() {
super("Could not find your region!");
}
}
並且此代碼塊無法正常運行
public Adventure(String file) {
try {
File inFile = new File(file);
Scanner scan = new Scanner(inFile);
int i = 0;
while (scan.hasNext()) {
String name = scan.nextLine();
pokemon[i] = name;
i++;
}
} catch (UnknownRegionException e) {
System.err.println(e);
}
}
我得到的錯誤如下
D:\Documents\Google Drive\Homework\1331\HW8>javac Adventure.java
Adventure.java:23: error: unreported exception FileNotFoundException; must be ca
ught or declared to be thrown
Scanner scan = new Scanner(inFile);
^
Adventure.java:63: error: unreported exception PokemonAlreadyExistsException; mu
st be caught or declared to be thrown
throw new PokemonAlreadyExistsException(message);
^
Adventure.java:78: error: unreported exception PokemonAlreadyExistsException; mu
st be caught or declared to be thrown
throw new PokemonAlreadyExistsException();
^
Adventure.java:84: error: unreported exception PartyIsFullException; must be cau
ght or declared to be thrown
throw new PartyIsFullException();
^
Adventure.java:99: error: unreported exception FileNotFoundException; must be ca
ught or declared to be thrown
PrintWriter outWriter = new PrintWriter(outFile);
^
5 errors
需要在方法簽名中捕獲或聲明已檢查的異常。 您正在捕獲UnknownRegionException
但是看到的錯誤表明代碼可能會引發其他一些異常,例如FileNotFoundException
和PokemonAlreadyExistsException
以及PartyIsFullException
。 因此,這些要么需要捕獲在您的catch
塊中,要么需要在方法簽名中聲明,如下所示:
public Adventure(String file) throws FileNotFoundException, PokemonAlreadyExistsException, PartyIsFullException {
在I / O相關方法(例如對文件進行操作)中通常會出現檢查異常。 擴展RuntimeException
未經檢查的異常更為常見,並且沒有必要的冗長語法。
編輯
即使您的代碼知道您的UnknownRegionException
, Scanner
也不知道,因此無法將其拋出。 掃描程序僅聲明它拋出FileNotFoundException
。 如果希望它的行為就像它拋出UnknownRegionException
一樣,則需要捕獲FileNotFoundException
並將消息包裝在UnknownRegionException
public Adventure(String file) throws UnknownRegionException {
try {
File inFile = new File(file);
Scanner scan = new Scanner(inFile);
int i = 0;
while (scan.hasNext()) {
String name = scan.nextLine();
pokemon[i] = name;
i++;
}
} catch (FileNotFoundException e) {
throw new UnknownRegionException(e.getMessage());
}
}
除此之外, Scanner
無法拋出一個異常,該異常是它聲明要拋出的異常的子類。 本質上, FileNotFoundException
知道IOException
因為它是IOException
的子類,但它不知道UnknownRegionException
因為UnknownRegionException
是它的子類。 您唯一的選擇是自己拋出異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.