java - 为什么我的自定义异常没有被重新抛出/捕获?
问题描述
所以我有一个名为 Digicel 的课程和另一个名为 AdminGui 的课程。我已将 Digicel 类导入到 AdminGui 类中,因为它们位于单独的包中。我的项目中还有其他类,但我认为不需要针对此问题提及它们。
我在 Digicel 类中有一个名为 addCustomer 的函数,它将客户的信息写入文本文件。但是我想检查文件中的记录,以确保客户的身份证号码是唯一的,并且文件中不存在。为此,我创建了一个名为 UniqueValueException 的自定义异常,它扩展了 Exception 类。
唯一值异常类
public class UniqueValueException extends Exception {
public UniqueValueException(String message) {
super(message);
}
}
在 Digicel 类中,我有用于写入文件的 addCustomer 函数和用于在文件中搜索相同客户 ID 的 checkCustomerUniqueValues。
检查客户唯一值功能
public static void checkCustomerUniqueValues(Customer c) throws UniqueValueException{
Scanner inFileStream = null;
String custID = "";
String name = "";
float creditBalance = 0;
String telephone = "";
String address = "";
try {
inFileStream = new Scanner(new File("Digicel_Customers.txt"));
while (inFileStream.hasNext()) {
custID = inFileStream.next();
name = inFileStream.next();
creditBalance = inFileStream.nextFloat();
telephone = inFileStream.next();
address = inFileStream.nextLine();
if (custID.equals(c.getCustID())) {
//inFileStream is closed in finally block
throw new UniqueValueException("Customer ID already exists.");
}
else if(telephone.equals(c.getTelephone().toString())){
throw new UniqueValueException("Telephone number already in use.");
}
}
}
catch (UniqueValueException e) {
e.printStackTrace();
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
finally{
if(inFileStream != null) {
try {
inFileStream.close();
}catch(Exception e) {
System.err.println("\nAn unexpected error occured.");
}
}
}
}
添加客户功能
public String addCustomer(Customer c) throws UniqueValueException {
FileWriter outFileStream = null;
Scanner input = null;
input = new Scanner(System.in);
try {
outFileStream = new FileWriter(new File("Digicel_Customers.txt"), true);
try {
checkCustomerUniqueValues(c);
}
catch(UniqueValueException e){
System.out.println("Inside addCustomer() method");
throw e;
}
catch(Exception e) {
throw e;
}
if(c.getCustID().length() != 11){
return "TRN is invalid - Length: " + c.getCustID().length();
}
String newCustomer = c.getCustID() + "\t" + c.getName() + "\t" + c.getCreditBalance() + "\t" + c.getTelephone().toString() + "\t" + c.getAddress() + "\n";
outFileStream.write(newCustomer);
System.out.println("Information saved successfully!");
super.addCustomer(c);
digicelCustomerCount++;
return("");
}
catch(Exception e) {
return("\nAn unexpected error occured.");
}
finally {
if(outFileStream != null) {
try {
outFileStream.close();
}catch(Exception e) {
System.err.println("\nAn unexpected error occured.");
}
}
if(input != null) {
input.close();
}
}
}
在 AdminGui 类中,我在按钮上有一个动作侦听器,用于传递文本字段的信息以在 Digicel 中添加客户功能。
addUserButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Customer c;
String returnString = "";
if(!customerIdText.getText().equals(" - - ") && !lastNameText.getText().equals("User Last Name") && !addressText.getText().equals("Address") && !phoneText.getText().equals("876-000-0000")){
c = new Customer(customerIdText.getText(), lastNameText.getText(), addressText.getText(), new Telephone(Integer.parseInt(phoneText.getText().substring(0,3)), Integer.parseInt(phoneText.getText().substring(4,7)), Integer.parseInt(phoneText.getText().substring(8,12))));
try{
returnString = adminUser.addCustomer(c);
if(returnString != ""){
JOptionPane.showMessageDialog(parentFrame,returnString + " "+ phoneText.getText() + "\nPrefix - " + phoneText.getText().substring(0,3),"Form Error",JOptionPane.ERROR_MESSAGE);
}
else{
JOptionPane.showMessageDialog(parentFrame,"Information Saved!","Form Submitted",JOptionPane.INFORMATION_MESSAGE);
}
}
catch(UniqueValueException e1){
JOptionPane.showMessageDialog(parentFrame,returnString,"Form Error",JOptionPane.ERROR_MESSAGE);
}
}
else{
JOptionPane.showMessageDialog(parentFrame,"All fields must be filled","Form Error",JOptionPane.ERROR_MESSAGE);
}
}
});
我的问题是在 checkCustomerUniqueValues 方法中,抛出了异常,但它没有在 addCustomer 方法中捕获,即使它在 try 块中被调用。checkCustomerUniqueValues 中抛出的异常的错误消息显示在终端中,但堆栈中的其余代码仍在运行。“信息保存成功!” 消息显示在底部。
OOPproject.teleCompanyPKG.UniqueValueException: Customer ID already exists.
at OOPproject.teleCompanyPKG.Digicel.checkCustomerUniqueValues(Digicel.java:182)
at OOPproject.teleCompanyPKG.Digicel.addCustomer(Digicel.java:121)
at OOPproject.guiPKG.AdminGui$6.actionPerformed(AdminGui.java:444)
at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1972)
at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2313)
at java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:405)
at java.desktop/javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262)
at java.desktop/javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:279)
at java.desktop/java.awt.Component.processMouseEvent(Component.java:6617)
at java.desktop/javax.swing.JComponent.processMouseEvent(JComponent.java:3342)
at java.desktop/java.awt.Component.processEvent(Component.java:6382)
at java.desktop/java.awt.Container.processEvent(Container.java:2264)
at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:4993)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2322)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4825)
at java.desktop/java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4934)
at java.desktop/java.awt.LightweightDispatcher.processMouseEvent(Container.java:4563)
at java.desktop/java.awt.LightweightDispatcher.dispatchEvent(Container.java:4504)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2308)
at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2773)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4825)
at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:772)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:715)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:95)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:745)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:743)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:742)
at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
Information saved successfully!
我真的很难解决如何解决它,因为我不知道为什么它没有被重新抛出。请发送帮助。
解决方案
您的checkCustomerUniqueValues
方法捕获所有 type 异常Exception
,并吞下它们:
} catch (Exception e) {
e.printStackTrace();
}
因为UniqueValueException
是 的子类型Exception
,所以 catch 块会捕获它,并阻止它传播到调用者。
推荐阅读
- python-3.x - Python:如何在函数的for循环中执行字符串中的变量?
- css - 如何快速创建VSCode 中的类
- r - geom_smooth 可以接受 glm 的逻辑变量吗?
- python - 问题的 Python 帮助
- angular - 在 Angular for Protractor 测试场景中使用 http 请求模拟特定方法
- javascript - 如何添加复选框计算
- python - If else 条件比较 2 列并在 Python pandas 数据框中插入一个新列
- confluence - 如何在使用 Atlassian SDK 开发 Confluence 宏时加快页面加载时间?batch.js 和 batch.css 最多需要 50 秒
- c# - 为什么我需要初始化字符串变量'name'?
- java - Android Q(API 级别 29)不加载 HTTPS 网站。给出错误:(net::ERR_ACCESS_DENIED)