Reputation: 2830
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?
Upvotes: 2
Views: 5814
Reputation: 11452
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!
Upvotes: 1
Reputation: 533530
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,
}
}
}
Upvotes: 5
Reputation: 6831
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 -
Upvotes: 0