简体   繁体   English

异常可以引发相同的异常吗?

[英]Can a exception throws the same exception?

Sorry if this could be a stupid question but i'm learning Java and i'm experiencing some problems with exceptions. 抱歉,这可能是一个愚蠢的问题,但是我正在学习Java,并且遇到了一些异常问题。 I have this code of my first project: 我的第一个项目有以下代码:

protected void makePurchase(int userId, Product item, int quantity) throws ItemNotBuyableException {        
    int id = item.getId();
    int count = 0;
    boolean flag = true;

    for (int i=0; i < quantity; i++) {
        try {
            catalog.sellProduct(id);
            count++;
        }
        catch (ItemNotBuyableException e) {
            flag = false;
        }
    }

    orders.addOrder(new Purchase(new GregorianCalendar(), id, item, item.getPrice(), count, userId));

    if (!flag)
        throw new ItemNotBuyableException();
}

Is it legit? 合法吗?

Yes it is legitimate. 是的,这是合法的。

Theoretically, you can catch it, do some more stuff that only your class knows how to do, then throw it to whoever is using you. 从理论上讲,您可以捕获它,做一些其他事情,只有您的班级知道该怎么做,然后将其扔给使用您的人。

try {
    catalog.sellProduct(id);
    count++;
}
catch (ItemNotBuyableException e) {
    doMoreStuff();
    //Better let other callers know so they can handle it appropriately
    throw e;
}

This is better: 这个更好:

protected void makePurchase(int userId, Product item, int quantity) throws ItemNotBuyableException {
    int id = item.getId();
    int count = 0;

    boolean flag = true;
    for (int i = 0; i < quantity; i++) {

        if(!catalog.sellProduct(id)) {
            flag = false;
            continue;
        }
        count++;
    }

    orders.addOrder(new Purchase(new GregorianCalendar(), id, item, item.getPrice(), count, userId));

    if (!flag)
        throw new ItemNotBuyableException();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM