Java 实现异常处理

标签 java exception

当用户尝试购买的商品数量多于可用商品时,我正在尝试实现 OutOfStockException。我不确定我的实现是否正确。您认为这合适吗?

public class OutOfStockException extends Exception {


    public OutOfStockException(){
        super();
    }

    public OutOfStockException(String s){
        super(s);
    }
}

这是我需要测试它的类:

import javax.swing.JOptionPane;

public class SwimItems {
    static final int MAX = 100;


    public static void main (String [] args)
    {
        Item [] items = new Item[MAX];
        int numItems;

        numItems = fillFreebies(items);
        numItems += fillTaxable(items,numItems);
        numItems += fillNonTaxable(items,numItems);

        sellStuff(items, numItems);
    }

    private static int num(String which) {
        int n = 0;
        do {
                       try{
            n=Integer.parseInt(JOptionPane.showInputDialog("Enter number of "+which+" items to add to stock:"));
                       }
                       catch(NumberFormatException nfe){
                           System.out.println("Number Format Exception in num method");
                       }
        } while (n < 1 || n > MAX/3);
        return n;
    }

    private static int fillFreebies(Item [] list)
    {
        int n = num("FREEBIES");
        for (int i = 0; i < n; i++)
                    try{
            list [i] = new Item(JOptionPane.showInputDialog("What freebie item will you give away?"),
            Integer.parseInt(JOptionPane.showInputDialog("How many do you have?")));
                    }
                    catch(NumberFormatException nfe){
                        System.out.println("Number Format Exception in fillFreebies method");
                    }
                    catch(ArrayIndexOutOfBoundsException e){
                        System.out.println("Array Index Out Of Bounds Exception in fillFreebies method");
                    }

        return n;
    }

    private static int fillTaxable(Item [] list, int number)
    {
        int n = num("Taxable Items");
        for (int i = number ; i < n + number; i++)
                    try{
            list [i] = new TaxableItem(JOptionPane.showInputDialog("What taxable item will you sell?"),
                Double.parseDouble(JOptionPane.showInputDialog("How much will you charge (not including tax) for each?")),
                    Integer.parseInt(JOptionPane.showInputDialog("How many do you have?")));
                    }
                    catch(NumberFormatException nfe){
                        System.out.println("Number Format Exception in fillTaxable method");
                    }
                    catch(ArrayIndexOutOfBoundsException e){
                        System.out.println("Array Index Out Of Bounds Exception in fillTaxable method");
                    }

        return n;
    }


    private static int fillNonTaxable(Item [] list, int number)
    {
        int n = num("Non-Taxable Items");
        for (int i = number ; i < n + number; i++)
                    try{
            list [i] = new SaleItem(JOptionPane.showInputDialog("What non-taxable item will you sell?"),
                    Double.parseDouble(JOptionPane.showInputDialog("How much will you charge for each?")),
                    Integer.parseInt(JOptionPane.showInputDialog("How many do you have?")));
                    }
                    catch(NumberFormatException nfe){
                        System.out.println("Number Format Exception in fillNonTaxable method");
                    }
                    catch(ArrayIndexOutOfBoundsException e){
                        System.out.println("Array Index Out Of Bounds Exception in fillNonTaxable method");
                    }

        return n;
    }


    private static String listEm(Item [] all, int n, boolean numInc)
    {
        String list = "Items:  ";
        for (int i = 0; i < n; i++)
        {
                    try{
            list += "\n"+ (i+1)+".  "+all[i].toString() ;
            if (all[i] instanceof SaleItem) list += " (taxable) ";
            if (numInc) list += " (Number in Stock: "+all[i].getNum()+")";
                    }
                    catch(ArrayIndexOutOfBoundsException e){
                        System.out.println("Array Index Out Of Bounds Exception in listEm method");
                    }
                    catch(NullPointerException npe){
                        System.out.println("Null Pointer Exception in listEm method");
                    }

        }
        return list;
    }



    private static void sellStuff (Item [] list, int n) {

        int choice;
        do {
                    try{
            choice = Integer.parseInt(JOptionPane.showInputDialog("Enter item of choice:  "+listEm(list, n, false)));
                    }
                    catch(NumberFormatException nfe){
                        System.out.println("Number Format Exception in sellStuff method");
                    }

        }while (JOptionPane.showConfirmDialog(null, "Another customer?")==JOptionPane.YES_OPTION);

        JOptionPane.showMessageDialog(null, "Remaining "+listEm(list, n, true));

        }

}

最佳答案

实现看起来不错;您不必在异常类中做太多事情。您可以考虑添加成员,了解缺货的商品、请求的数量以及发出请求时有多少库存,以便捕获异常的代码可以访问该信息。例如,这里我有一个库存商品代码:

public class OutOfStockException extends Exception {

    private int stockCode;

    public OutOfStockException(int stockCode){
        super();
        this.stockCode = stockCode;
    }

    public OutOfStockException(String s){
        super(s);
        this.stockCode = stockCode;
    }

    public int getStockCode() {
        return this.stockCode;
    }
}

然后您可以像这样创建一个:

throw new OutOfStockException(StockCodes.WIDGET, "Out of widgets");

但这取决于你,那时它就像其他任何东西一样只是类设计。

很多时候,对于这类事情,我包含具有各个部分的构造函数,然后让类本身为底层异常生成消息getMessage 消息。所以:

public class OutOfStockException extends Exception {

    private int stockCode;

    public OutOfStockException(int stockCode){
        super("Out of " + StockCodes.getDescription(stockCode));
        this.stockCode = stockCode;
    }

    public int getStockCode() {
        return this.stockCode;
    }
}

// Throwing one:
throw new OutOfStockException(StockCodes.WIDGETS);

但此时这只是类设计。

除此之外,这有点偏离主题,但在我看来,某件商品缺货是一种正常情况,而不是特殊情况;您确定异常确实是建模的正确方法吗?

关于Java 实现异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2488109/

相关文章:

java - 如何正确关闭资源?

java - 检查finally中是否执行了try或执行了catch

Java int 数据类型在使用二进制值时自动转换

java - 字符串操作,从同一行提取某些值

Flutter:未处理的异常:在初始化绑定(bind)之前访问了 ServicesBinding.defaultBinaryMessenger

java ExecutorService 如何处理超时

java - 任何方法重载都是编译时多态性吗?

java - java中如何从链表中删除数据

java - BindingResult 和 bean 名称的普通目标对象都不能用作请求属性,我不知道为什么

c++ - 处理异常后阻止线程在分离时调用 std::terminate()