简体   繁体   English

如何在Java中的catch块中调用方法?

[英]How do you call a method from a catch block in java?

Requirement: If there are any exceptions, call a method that re verifies data 要求:如果有任何异常,请调用重新验证数据的方法

My implementation: 我的实现:

private void one() {
    try {
        //Valid data
    }catch(Exception e) {
    two();
    }
}

private void two() {
     //Process data with another input
     //On entry,
     one();
}

I realize that my usage is incorrect. 我意识到我的用法不正确。 How should I be handling this? 我应该如何处理呢?

You can do it exactly the way you suggest, using recursion. 您可以使用递归完全按照您的建议进行操作。 I don't see what the problem is. 我看不出问题是什么。 Personally, using a loop is usually simpler than using recursion. 就个人而言,使用循环通常比使用递归更简单。 I wouldn't just catch all Exception's however. 但是,我不仅会抓住所有的例外。 You are likely to want to handle different exceptions differently. 您可能希望以不同的方式处理不同的异常。

private void one() {
  while(true) {
    try {
        //Valid data
        break;
    }catch(InvalidArgumentException e) { // or what ever you expect.
        two();
    }
  }
}

private void two() {
     //Process data with another input
     //On entry,
}

or even 甚至

private void one() {
  while(true) {
    try {
        //Valid data
        break;
    } catch(InvalidArgumentException e) { // or what ever you expect.
        // Process data with another input
        // On entry,
    }
  }
}

Better way of doing it would be, Check data in a while loop somewhere else before you use data in method one() , While it's not valid keep correcting until it's valid and than give it to one() . 更好的方法是,在使用one()方法中的数据之前,在其他地方的while循环中检查数据,虽然无效,但要先进行校正直到有效,然后再将其提供给one()

After your comments in question 在您有问题的评论之后

make your error variable to be an class level and reset it in method two() like this, 使您的error变量成为类级别,并在方法two()中将其重置,如下所示:

private void two() {
     this.error = false;
     //Process data with another input
     //On entry,
     one();
}

Good luck! 祝好运!

The usage you showed in the code is correct - What makes you think this is not correct ? 您在代码中显示的用法是正确的-是什么让您认为这是不正确的?

However, I see that you are recalling the original method in the catch on which I have comments - 但是,我看到您想起了我对此发表评论的文章中的原始方法-

  1. If it keeps on throwing the exception, it will lead to Stack overflow. 如果继续抛出异常,将导致堆栈溢出。
  2. You would like to have some preventive / different logic to check unless this is time dependent or the per-conditions changed itself during the calls. 您希望有一些预防性/不同的逻辑来检查,除非这与时间有关或在调用过程中每个条件本身都发生了变化。
  3. You should consider an exit condition in case you stuck into loop. 您应该考虑退出条件,以防陷入循环。

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

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