【问题标题】:Why is my custom exception not being rethrown/caught?为什么我的自定义异常没有被重新抛出/捕获?
【发布时间】:2021-11-06 20:39:53
【问题描述】:

所以我有一个名为 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!

我真的不知道如何修复它,因为我不知道为什么它没有被重新抛出。请发送帮助。

【问题讨论】:

  • 我们在这里捕获它:} catch (Exception e) { e.printStackTrace(); }。由于UniqueValueException extends Exceptioncatch (Exception ...) 也将捕获UniqueValueExceptions。

标签: java swing oop exception non-static


【解决方案1】:

您的checkCustomerUniqueValues 方法捕获Exception 类型的所有异常,并吞下它们:

        } catch (Exception e) {
            e.printStackTrace();
        }

因为UniqueValueExceptionException 的子类型,所以catch-block 会捕获它,并阻止它传播到调用者。

【讨论】:

  • 我刚刚在 Exception 捕获上方添加了 UniqueValueException 捕获,但结果仍然相同。
  • @Ashley 我对此表示怀疑。请编辑帖子,添加minimal reproducible example 并分享更新后的代码。
  • @Ashley:你不应该在抛出异常的方法中捕捉到这个异常,而且你永远也不应该捕捉到Exception永远。始终捕获特定异常。
  • 在删除所有异常捕获块并从 checkCustomerUniqueValues 方法中删除 UniqueValueException 捕获块之后。它现在正在工作。谢谢。
  • @DontKnowMuchButGettingBetter:我不同意你所说的“你永远不应该抓住Exception永远”。首先,捕获异常并抛出包装异常是很常见的。其次,有时即使不识别特定的异常类型也可以(并且希望)处理异常;例如,在“进程管理器”类型的系统中,如果进程抛出异常,管理器应该捕获该异常并将该进程标记为失败(使用适当的元数据)。
猜你喜欢
  • 2014-08-16
  • 2010-11-16
  • 2012-01-22
  • 1970-01-01
  • 2020-11-04
  • 1970-01-01
  • 2020-11-16
相关资源
最近更新 更多