如何使用函数处理 catch 块?

How to handle catch block with functions?

我很想知道,假设我有一个函数说 myFunction()。查看此示例:

public void myFunction() {
    try {
        for (int i = 0; i <= 15; i++) {
            System.out.println("Counting: " + i);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

现在,如果在此函数中捕获到任何类型的错误,我想像这样处理此错误,然后重新开始 myFunction()。怎么做?

我的意思是,如何在 catch(Exception e) 中包含该函数,以便它可以重新启动该函数?可能吗?

不胜感激!

public void myFunction() {
    boolean successful = false;
    int retryCount = 0;
    while(retryCount < 5 && !successful) {
        try {
            for (int i = 0; i <= 15; i++) {
                System.out.println("Counting: " + i);
            }
            successful = true;
        } catch (Exception e) {
            e.printStackTrace();
            successful = false;
            retryCount++;
        }
    }
}

这是 http://tutorials.jenkov.com/java-exception-handling/basic-try-catch-finally.html#catch-or-propagating-exceptions 中有关捕获或传播异常的问题。我还建议您编写自定义异常处理问题并阅读该教程。以下是您必须遵守的事项

It depends on the situation. In many applications you can't really do much about the exception but tell the user that the requested action failed. In these applications you can usually catch all or most exceptions centrally in one of the first methods in the call stack. You may still have to deal with the exception while propagating it though (using finally clauses). For instance, if an error occurs in the database connection in a web application, you may still have to close the database connection in a finally clause, even if you can't do anything else than tell the user that the action failed. How you end up handling exceptions also depends on whether you choose checked or unchecked exceptions for your application. There is more on that in other texts in the error handling trail.

我建议您以这种方式传播异常:

public void myFunction() thows MyException{

try{

for(int i=0; i<=15;i++){
    System.out.println("Counting: "+i);     
    }

}catch(Exception e){
    e.printStackTrace();
    Thows new MyException()
}

}

public class MyException extends Exception {
    public MyException(String message) {
        super(message);
    }
}

然后你可以在一个上下文中执行你的函数,如果问题是你想要重新启动的原因,你可以重新启动

 begin for example a while lool

try {
   Function();
}catch MyException {
   start again
}