很抱歉,如果这可能是一个愚蠢的问题,但我正在学习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 < 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();
}
Run Code Online (Sandbox Code Playgroud)
它合法吗?
是的,这是合法的.
从理论上讲,你可以抓住它,做一些只有你的班级知道该怎么做的东西,然后把它扔给任何使用你的人.
try {
catalog.sellProduct(id);
count++;
}
catch (ItemNotBuyableException e) {
doMoreStuff();
//Better let other callers know so they can handle it appropriately
throw e;
}
Run Code Online (Sandbox Code Playgroud)