如何在java中继续执行try catch语句 [英] How to continue execution of a try catch statement in java

查看:862
本文介绍了如何在java中继续执行try catch语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Java:Try-Catch-Continue?

我正在阅读来自文本文件的信息,如果读取的类型无效,我希望我的代码抛出异常。但是,在找到例外之后,我无法弄清楚如何让程序继续下去

I'm reading in information from a text file and I want my code to throw an exception if there is an invalid type being read. However, I can't figure out how to have my program continue after an exception has been found

    while(input.hasNext()) {
        try{

        type = input.next();
        name = input.next();
        year = input.nextInt();


        } catch(InputMismatchException ex)
          {
            //System.out.println("** Error: Invalid input **");
            //code to make program continue

          }

    }


推荐答案

你可以让线程离开 catch 块 - 之后的代码执行会继续。如果要在 catch 块之后跳过代码,可以在<$ c $中使用 continue 关键字c> while 循环...

You can either just let the thread leave the catch block - code execution will continue after that. If you want to skip the code after the catch block, you can use the continue keyword within a while loop...

如果要在...之后检索年份检索名称失败并发生异常,那么您将不得不在每个<$ code> try ... catch c $ c> input.next ...()语句。在抛出异常的时候你无法重新启动执行。

If you want to retrieve a year after retrieving the name failed with an exception, then you will have to put a try ... catch around each input.next...() statement. You cannot restart execution at the point the exception has been thrown.

这篇关于如何在java中继续执行try catch语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆