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 -
- If it keeps on throwing the exception, it will lead to Stack overflow.
- 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.
- You should consider an exit condition in case you stuck into loop.
精彩评论