java - 抛出并捕获自定义异常

标签 java file exception fileopendialog

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

 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");
   }

 }

最佳答案

看起来您正在对选择器的结果进行赋值而不是测试。

代替

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);
    }
}

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

关于java - 抛出并捕获自定义异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30046807/

相关文章:

c++ - 一次写入多个文件

java - 使用 throws 将异常传播到被调用的方法

java - XML 在 Android 中不显示

java - 在 jframe 中添加日期选择器?

c# - HttpModule/HttpApplication 测试 url 是否为文件请求

node.js - 使用 FS 文件系统的 Node、Webpack 和 React 路由

java - 同一类上的 isInstance() 在异常处理期间返回 false

javascript - 为什么 setInterval() 会忽略错误?

java - 数组有时无法按预期工作

java - 使用 spring session ID cookie 进行单点登录?