Is there any other way for people to recover from such errors when you want to repeat the operation after handling the exception?
Yes, in the calling code. Let the caller of this method decide whether they need to repeat the logic or not.
UPDATE:
To clarify, you should catch exceptions only if you really can handle them. Your code basically says:
"I have no idea what happened, but all I did is explode ... so let's do it again."
Eliminate certain errors from which you can recover, and let the remaining bubbles go to the next level. Any exceptions that do this to the very top are true errors at this point.
UPDATE 2:
So, instead of continuing a rather lengthy discussion with the help of comments, which I will describe in the example with a semi-pseudo-code.
The general idea is that you just need to restructure the code for testing and improve the user interface a bit.
//The main thread might look something like this try{ var database = LoadDatabaseFromUserInput(); //Do other stuff with database } catch(Exception ex){ //Since this is probably the highest layer, // then we have no clue what just happened Logger.Critical(ex); DisplayTheIHaveNoIdeaWhatJustHappenedAndAmGoingToCrashNowMessageToTheUser(ex); } //And here is the implementation public IDatabase LoadDatabaseFromUserInput(){ IDatabase database = null; userHasGivenUpAndQuit = false; //Do looping close to the control (in this case the user) do{ try{ //Wait for user input GetUserInput(); //Check user input for validity CheckConfigFile(); CheckDatabaseConnection(); //This line shouldn't fail, but if it does we are // going to let it bubble up to the next layer because // we don't know what just happened database = LoadDatabaseFromSettings(); } catch(ConfigFileException ex){ Logger.Warning(ex); DisplayUserFriendlyMessage(ex); } catch(CouldNotConnectToDatabaseException ex){ Logger.Warning(ex); DisplayUserFriendlyMessage(ex); } finally{ //Clean up any resources here } }while(database != null); }
Now, obviously, I have no idea what your application is trying to do, and this is certainly not an example of production. I hope you get a general idea. Rebuild the program to avoid unnecessary gaps in the application flow.
Cheers, Josh
Josh
source share