简体   繁体   English

java异常处理和继续

[英]java exception handling and continuation

I have a Java Program where I get data from a different source. 我有一个Java程序,可以从其他来源获取数据。 some times while reading I see Exception and the program is exiting. 有时在阅读时我看到异常,程序正在退出。 Mine is in a program that runs every 10minutes. 我的程序每10分钟运行一次。

Public static void main(Strings[] args)
{
...readsource();
}

Private static void readsource() throws IOException
{
...
}

Issue: I am able to get/See the Exception. 问题:我能够获得/看到异常。 But I want the program to continue To that what is the best logic? 但是我希望程序继续执行。最好的逻辑是什么? I dont see try-catch-finally also is not addressing ..I want the program to continue even after seing the exception (I mean the next iteration should continue). 我看不到try-catch-finally也没有解决..我希望程序即使遇到异常后仍继续运行(我的意思是下一次迭代应该继续)。 This looks to be a Basic issue not sure how to address this... 这似乎是一个基本问题,不确定如何解决此问题...

Then you need to catch the exception, which you are currently not doing. 然后,您需要捕获当前未执行的异常。

try  {
    readsource();
} catch (IOException e) {
   // do something, never catch an exception and not do anything
}

//continue.

Note that exceptions usually indicate something is wrong. 请注意,异常通常表示出了什么问题。 Unless you are going to do something about the exception, it might be better to fix the condition causing the exception.... 除非您要对异常做点什么,否则最好修复导致异常的条件。

You have to provide an error handler in your method, ie surround the call to readsource() with a try-catch block. 您必须在方法中提供一个错误处理程序,即用try-catch块包围对readsource()的调用。

   public static void main(Strings[] args)
   {
      try{
         ...readsource();
      }
      catch(IOException ioe){
           //handle the error here,e.g don't do anything or simply log it
      }
    }

如果您没有在catch块中抛出异常,则执行将从该catch块的末尾掉落并继续执行,就好像没有异常一样。

If you mean you'd like to recall the method wether an Exception was thrown or not just place this in a while loop ie: 如果您是想回想抛出异常的方法,或者不只是将其放置在while循环中,即:

Public static void main(Strings[] args)
{
    boolean run=true;
    while(run) {
    try {
            System.out.print("Hello,");
            readsource();
            throw new IOException();
            if(1==2)run=false;//stop the loop for whatever condition
        } catch(IOException ioe) {
            ioe.printStackTrace();
        }
        System.out.println(" world!");
    }
   }

}

Private static void readsource() throws IOException
{
...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM