有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么我的自定义异常没有被重新调用/捕获?

所以我有一个叫做Digicel的类和另一个叫做AdminGui的类。我已将Digicel类导入AdminGui类,因为它们位于不同的包中。在我的项目中还有其他课程,但我不认为在这个问题上需要提及它们

我在Digicel类中有一个名为addCustomer的函数,它将客户信息写入文本文件。但我想检查文件中的记录,以确保客户的id号是唯一的,并且文件中不存在。为此,我创建了一个名为UniqueValueException的自定义异常,它扩展了exception类

唯一值异常类

public class UniqueValueException extends Exception {
    public UniqueValueException(String message) {
        super(message);
    }
}

在Digicel类中,我有一个addCustomer函数,它会写入文件,还有一个checkCustomerUniqueValues,它会在文件中搜索相同的客户Id

检查“客户唯一值”功能

    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中添加customer函数

        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!

我真的很困惑如何修复它,因为我不知道为什么它没有被重新修复。请派人来帮忙


共 (1) 个答案

  1. # 1 楼答案

    您的checkCustomerUniqueValues方法捕获Exception类型的所有异常,并将其吞并:

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

    因为UniqueValueExceptionException的一个子类型,所以catch块会捕获它,并阻止它向调用方传播