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