为了账号安全,请及时绑定邮箱和手机立即绑定

如何捕获异常并且不停止代码执行

如何捕获异常并且不停止代码执行

不负相思意 2022-11-02 17:01:12
我想捕获 InputMissmatchException 但不停止重新执行代码(我希望 while 循环再次重新运行,直到给出适当的输入)整数选择 = 0;布尔循环=真;    while(loop){        printInstruction();        choice = scanner.nextInt();        //catch InputMissmatchException        switch(choice){            case 0:                loop = false;                break;            case 1:                addCustomer(mohamad,sgbl);                break;            case 2:                deleteCustomer(sgbl);                break;            case 3:                seeInfo(sgbl);                break;            case 4:                makeTransaction(mohamad);                break;            case 5:                seeTransactionLog(mohamad);                break;            default:                System.out.println("try again");        }    }
查看完整描述

1 回答

?
郎朗坤

TA贡献1921条经验 获得超9个赞

int a = -1;

while(true)

{

  try

  {

      Scanner in = new Scanner(System.in);

      a = in.nextInt();

  }

  catch(InputMismatchException e)

  {

      e.printStackTrace();   

  }


  //Your switch statement 

 }

顺便说一下,a 的默认值设置为 -1。如果发生异常,则进入 switch case 时的值将是 -1。


int a = -1;

while(true)

{

  try

  {

      Scanner in = new Scanner(System.in);

      a = in.nextInt();

  }

  catch(InputMismatchException e)

  {

      e.printStackTrace();   

      continue;

  }


  //Your switch statement 

 }

如果您使用 continue 则循环的当前迭代将停止并运行下一次迭代


查看完整回答
反对 回复 2022-11-02
  • 1 回答
  • 0 关注
  • 53 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信