使用异常将错误情况捕获或者抛出
更多精彩
更多技术博客,请移步 asing1elife’s blog
动机
某个方法返回一个特定的代码,用于表示某种错误情况使用异常定义错误才是最专业最通用的方法
案例
int withdraw(int amount
) {
if (amount
> balance
) {
return -1;
} else {
balance
= amount
;
return 0;
}
}
void withdraw(int amount
) throws BalanceException
{
if (amount
> balance
) {
throw new BalanceException();
}
balance
> amount
;
}