English 中文(简体)
Java 执行例外处理
原标题:Java implementing Exception Handling

我正试图对用户试图购买比现有多件物品时采用“外部冲击”。 我不敢确定我的执行情况是否正确。 这是否看你?

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 += "
"+ (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");

但是,这取决于你们,当时,它只是像其他东西一样的阶级设计。

在许多时候,由于这些事情,I only<>em> > 包括各个部分的建筑商,然后该类别本身生成以下基本信息:ExceptiongetMessage。 因此:

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

但此时此刻,这又只是一个阶级设计。

除此以外,这只是稍微偏离,但在我看来,在某个项目上,似乎并非例外,而是正常的情况;你们是否确信一个例外是正确模式?

问题回答

是的,你的例外情况得到了正确执行。

然而,我建议在其中列入更多信息:

  • the product in question
  • the attempted number of items to order
  • the actual number of remaining items

例如,如果“Bike”产品有2个剩余物项,但1个试图订购3个,则该例外将予以制造,并像其他产品一样被抛弃。

throw new OutOfStockException(product, requestedQuantity, actualQuantity)

你的例外情况是ok。

页: 1 课程。

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

它是一部法典,在做事前必须检查这几类人的情况(我不相信上述姓名是有意义的)。 为什么不能凌驾上适当次等舱位的上述适当方法。

我不同意在此使用例外。 你们只应当使用一种特殊条件,就像名称所建议的那样,而不是为了控制流动,因为这将使你的法典更加令人愉快地阅读。 此外,联合核查机制无法优化例外情况,因此执行速度要慢得多。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...