Java 异常是否可以引发相同的异常?
很抱歉,这可能是一个愚蠢的问题,但我正在学习Java,遇到了一些异常问题。我有我第一个项目的代码:Java 异常是否可以引发相同的异常?,java,exception,Java,Exception,很抱歉,这可能是一个愚蠢的问题,但我正在学习Java,遇到了一些异常问题。我有我第一个项目的代码: 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
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();
}
合法吗?是的,合法
理论上,你可以抓住它,做一些只有你的类知道如何做的事情,然后把它扔给使用你的人
try {
catalog.sellProduct(id);
count++;
}
catch (ItemNotBuyableException e) {
doMoreStuff();
//Better let other callers know so they can handle it appropriately
throw e;
}
这样更好:
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();
}
不检查微小的编码错误,为什么不呢?您甚至可以保存原始异常并重新播放它。事实上,在某些情况下这会更好,因为它保留了原始的异常堆栈跟踪。通常,如果发生异常,您将不会继续下一个代码,需要继续处理。sellProduct方法最好返回相应的值,而不是异常。为什么不让该方法返回布尔值?@W.K.S-那么sellProduct为什么不返回布尔值呢?为什么会有异常呢?这是我的任务的一个要求SmartMouse在添加订单和抛出异常之前正在运行整个for循环。您的代码在sellProduct抛出的第一个异常情况下退出。是的,我知道了,将更改这将起作用,但我建议描述您建议更改sellProduct签名的更改,以及为什么您认为这是一个更好的解决方案。另外,你们不应该因为一个项目的失败而爆发。因为异常应该发生在异常情况下,但他的方法看起来并不例外。他只需要中断,在这种情况下不需要更多,因此没有必要抛出异常。更好的解决方案可能是在循环之前检查异常。