Reputation: 1865
Here's a question where my real world programming inexperience shines through. I have a function which makes a call to three other functions:
Public Sub StartService()
RunSearch()
SaveMessages()
DeleteMessages()
End Sub
within each of the methods RunSearch(), SaveMessages() and DeleteMessages()
I am using Try Catch statements to catch errors. Right now I catch the error and write to an error log when RunSearch()
errors out, but I'm also get two errors from SaveMessages()
and DeleteMessages()
because these functions are dependent upon RunSearch()
not returning an error. I am trying to build good a error catching foundation so I don't just want to kill the app when there's an error. My question is this: How can I gracefully stop execution if an error occurs in RunSearch()
.
Upvotes: 2
Views: 1984
Reputation: 55907
Why does RunSearch
not rethrow the exception after logging the problem?
If you don't want to call SaveMessages()
if RunSearch()
fails then don't code it that way.
My general thought is that each method's interface is specifying a "protocol". It must state its behaviour in the event of problems. Approaches include:
Upvotes: 5
Reputation: 4227
It seems like you might not need low-level method-level error handlers, but only an high/application-level handler. If all your catch blocks for each method are the same, I'd suggest switching to a high-level error handler. As a general rule, you only want to catch Exceptions that you can explicitly handle, or catch them at the last oppurtunity for logging purposes, and to prevent untidy application crashses.
This is how I would approach it
public void StartService()
{
try
{
RunSearch();
SaveMessages();
DeleteMessages();
}
catch(Exception ex)
{
//Do Nothing or Log ex
}
}
public void RunSearch()
{
//No error handler here, as this method cannot recover from exceptions
//RunSearch functionality
}
Upvotes: 1
Reputation: 1483
You should not use exceptions to control program flow. Use return values instead. Throwing and catching exceptions is expensive and should only be used to report truly unexpected conditions in your code.
David Stratton's answer above is a much better solution.
Upvotes: 0
Reputation: 32179
You could rethrow the method exceptions after you've done your logging, then wrap your RunSearch() method inside a try/catch block so that the next two methods don't run.
Upvotes: 1
Reputation: 73564
One possible option would be to change the RunSearch method to return a Boolean - True if successful, and False if an error occurred that would block the other two functions.
Then you could do this:
Public Sub StartService()
If RunSearch() Then
SaveMessages()
DeleteMessages()
End If
End Sub
Upvotes: 3