[英]I am trying to create a file via a button press but i keep running into an error
我正在創建支票簿,並且無法為每個單獨的帳戶創建要寫入的文件。 當我嘗試創建文件時,出現錯誤“未報告的異常IOException;必須捕獲或聲明為拋出”。 我試圖聲明我的動作偵聽器方法引發異常,但這會使動作偵聽器方法不再起作用。 然后,我嘗試創建一個單獨的方法來創建文件,並通過按按鈕調用它,但是我仍然遇到相同的錯誤
這是我的代碼:
public void actionPerformed(ActionEvent e) {
...
if (e.getSource() == create) {
creatNewAccount(name3.getText());
BALANCE = Double.parseDouble(name2.getText());
}
}
public void creatNewAccount(String s) throws IOException {
FileWriter fw = new FileWriter(s + ".txt", false);
}
IOException
是一個檢查的異常。 鑒於您是在ActionListener
調用它,因此無法拋出異常,因此您需要捕獲它。
try {
creatNewAccount(name3.getText());
} catch (IOException e) {
e.printStackTrace();
// more exception handling
}
creatNewAccount
被聲明為可能拋出IOException
。 IOException
不是RuntimeException
,因此您必須捕獲它。
if (e.getSource() == create) {
try {
creatNewAccount(name3.getText());
} catch (IOException ie) {
ie.printStackTrace();
// handle error
}
BALANCE = Double.parseDouble(name2.getText());
}
有關更多信息,請閱讀有關捕獲或指定需求以及捕獲和處理異常的信息 。
我注意到了其他一些事情:-您要查找的詞是create ,而不是creat 。 -您正在為BALANCE
分配某些內容。 大寫名稱通常為常量保留。 考慮重命名此可變balance
。 -為您的文本字段考慮更多描述性名稱。 name2
和name3
並沒有說太多。
在actionPerformed()
您需要在createNewAccount
調用周圍放置try / catch塊。 一旦捕獲到異常,您要執行的操作就由您自己決定–一件容易的事是將其包裝到不需要捕獲的RuntimeException
中(但可能會使您的過程RuntimeException
,直到您做一些更復雜的事情為止)。
public void actionPerformed(ActionEvent e) {
...
if (e.getSource() == create) {
try {
creatNewAccount(name3.getText());
} catch( IOException ioe) {
System.err.println("Whoops! " + ioe.getMessage());
throw new RuntimeException("Unexpected exception", ioe);
}
BALANCE = Double.parseDouble(name2.getText());
}
}
您可能只需要在方法內部捕獲異常:
public void creatNewAccount(String s) {
try{
FileWriter fw = new FileWriter(s + ".txt", false);
} catch (IOException e){
//TODO something to handle the error
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.