2

我有一种方法可以通过从“文件打开”对话框中选择来加载客户文件,并且它可以工作,除非我单击“取消”按钮。即使我按下取消按钮,它仍会加载所选文件。如果单击取消按钮,我想加载自定义异常。请对如何在我的方法中实现自定义异常有任何帮助吗?谢谢

 private void loadCustomerActionPerformed(java.awt.event.ActionEvent evt) {
   Customer customerfile = null;
   try {

     final JFileChooser chooser = new JFileChooser("Customers/");
     int chooserOption = chooser.showOpenDialog(null);
     chooserOption = JFileChooser.APPROVE_OPTION;

     File file = chooser.getSelectedFile();
     ObjectInputStream in = new ObjectInputStream(
       new FileInputStream(file)
     );

     customerfile = (Customer) in .readObject();

     custnameTF.setText(customerfile.getPersonName());
     custsurnameTF.setText(customerfile.getPersonSurname());
     custidTF.setText(customerfile.getPersonID());
     custpassidTF.setText(customerfile.getPassaportID());
     customertellTF.setText(customerfile.getPersonTel());
     customermobTF.setText(customerfile.getPersonMob());
     consnameTF.setText(customerfile.getConsultantname());
     conssurnameTF.setText(customerfile.getConsultantsurname());
     considTF.setText(customerfile.getConsulid());

     in .close();

   } catch (IOException ex) {
     System.out.println("Error Loading File" + ex.getMessage());
   } catch (ClassNotFoundException ex) {
     System.out.println("Error Loading Class");
   } finally {
     System.out.println("Customer Loaded");
   }

 }
4

4 回答 4

3

看起来您是在做作业,而不是对选择器的结果进行测试。

代替

chooserOption = JFileChooser.APPROVE_OPTION;

你应该有

if (chooserOption == JFileChooser.APPROVE_OPTION) {
    // handle open file
} else {
    throw new CancelException();
}

编辑

作为对评论的回应,异常应该扩展 Exception(用于检查的异常)、RuntimeException(用于未检查的异常)或这些类之一的后代。此级别的唯一区别是您不需要throws在方法签名中声明未经检查的异常。您的异常看起来像这样

public class CancelException extends Exception {

    public CancelException() {
    }

    public CancelException(String message) {
        super(message);
    }
}

另一条评论 - 例外情况应用于例外情况。使用它们来实现逻辑通常被认为是不好的做法——你真的需要使用异常吗?

于 2015-05-05T07:40:52.737 回答
2

让你的方法声明抛出你的异常:

private void loadCustomerActionPerformed(java.awt.event.ActionEvent evt)
    throws CustomException {

你总是APPROVE_OPTION给选择器选项:

 chooserOption = JFileChooser.APPROVE_OPTION; 

您必须制作对话框按钮侦听器才能修改此变量并添加条件:

if (chooserOption == JFileChooser.APPROVE_OPTION) {
    // load file
} else {
    throw new CustomException("ERROR MESSAGE");
}

你的CustomException班级必须看起来像:

class CustomExceptionextends Exception {
    public CustomException(String msg) {
        super(msg);
    }
}
于 2015-05-05T07:42:07.223 回答
1

您不应将任何内容分配给chooserOption. 您应该使用 的返回值JFileChooser.showOpenDialog(),它包含有关对话框显示结果的信息。例子:

int chooserOption = chooser.showOpenDialog(null);
if (chooserOption == JFileChooser.CANCEL_OPTION) {
   // throw your exception (or do some other actions) here
}
于 2015-05-05T07:43:21.887 回答
0

您没有使用选择器选项,一旦它选择了值,只需添加一个 if 条件来检查选择器选项值,如果选择,则执行否则抛出您的异常

于 2015-05-05T07:37:35.300 回答