Java实现异常处理

时间:2010-03-21 18:06:51

标签: java exception-handling 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));

        }

}

4 个答案:

答案 0 :(得分:4)

实施看起来很好;你不必在异常类中做太多事情。您可以考虑添加成员以查找缺货的内容,请求的数量以及请求时库存中有多少成员,以便捕获异常的代码可以访问该信息。例如,我在这里有一个股票代码:

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");

但这取决于你,在那一点上它就像其他任何类的设计一样。

很多时候,通过这些事情,我包含具有各个部分的构造函数,然后让类本身为底层Exception 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);

但是那时它只是阶级设计。

所有这一切都放在一边,这有点偏离主题,但在一件物品上缺货似乎是一种正常的情况,而不是一个特殊的情况;你确定一个例外真的是建模的正确方法吗?

答案 1 :(得分:1)

我不同意这里使用Exception。您应该只使用一个用于特殊条件,因为命名法建议而不是控制流程,因为这将使您的代码阅读更加愉快。此外,异常不会通过JVM进行优化,因此执行速度要慢得多。

答案 2 :(得分:0)

是的,您的例外已正确实施。

但是,我建议在其中加入更多信息:

  • 有问题的产品
  • 尝试订购的商品数量
  • 剩余物品的实际数量

例如,如果产品“Bike”有2个剩余项目,但是其中一个尝试订购3个,那么将构造并抛出异常

throw new OutOfStockException(product, requestedQuantity, actualQuantity)

答案 3 :(得分:0)

您的异常看起来不错。

我不确定您的SaleItemTaxableItem课程。

if (all[i] instanceof SaleItem) list += " (taxable) ";

是一种代码气味 - 在做某事之前必须检查类的实例(并且鉴于上述情况,我不确定这些名称是否有意义)。为什么不覆盖类上的适当方法来自动为适当的子类执行上述操作。