开发者

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

开发者 https://www.devze.com 2023-04-04 14:50 出处:网络
Requirement: If there are any exceptions, call a method that re verifies data My implementation: private void one() {

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().

After your comments in question

make your error variable to be an class level and reset it in method two() like this,

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.
0

精彩评论

暂无评论...
验证码 换一张
取 消