gpt4 book ai didi

Java,异常,最好的方法,考试准备

转载 作者:行者123 更新时间:2023-11-30 02:43:02 24 4
gpt4 key购买 nike

我正在准备基础编程考试。我现在正在研究异常,但似乎不知道如何最好地使用它。我给你第一个代码,然后是第二个代码,我尝试进行检查异常。任何对此的意见都会让我感激不尽!

无异常(exception):

public boolean uttak(int species, int kroner, int skilling) {
if (species<=this.species && kroner<=this.kroner && skilling <=this.skilling)
{
this.species -=species;
this.kroner -=kroner;
this.skilling -=skilling;
return true;
}
else return false;

还有我困惑的异常(exception):

public void uttak(int species, int kroner, int skilling){
try{
if (species<=this.species && kroner<=this.kroner && skilling <=this.skilling)
{
this.species -=species;
this.kroner -=kroner;
this.skilling -=skilling;
}
}
catch (Exception e){
System.err.println ("Withdrawals can not be done when there is" +
" insufficient money in the machine.");
}

最佳答案

您可能正在寻找这样的东西:

// custom checked exception type
public class WithdrawalException extends Exception {
public WithdrawalException(String msg) {
super(msg);
}
}
public boolean uttak(int species, int kroner, int skilling) throws WithdrawalException { // checked exceptions need to be declared in the throws clause 
if (species<=this.species && kroner<=this.kroner && skilling <=this.skilling)
{
this.species -=species;
this.kroner -=kroner;
this.skilling -=skilling;
return true;
}
else
// throw an exception
throw new WithdrawalException("Withdrawals can not be done when there is insufficient money in the machine.");
}

并在调用代码中使用它,如下所示

try {
uttak(i1, i2, i3);
} catch (WithdrawalException ex) {
System.err.println("Something went wrong. Message: "+ex.getMessage());
}

关于Java,异常,最好的方法,考试准备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41085591/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com