Reputation: 9969
All of us use the try catch blocks. But what is the best way of handling errors within custom functions?
Display a messagebox to the user when the exception is thrown (if possible within the function), or return a value indicating that an error was found within the function?
Upvotes: 2
Views: 463
Reputation: 985
Do not catch an exception that you cannot do something about. Code that is littered with try/catch blocks is difficult to read, and means that your exception handling code is not contained in one place for ease of maintenance.
If you are just logging the exception or alerting the user, this should be done at the top of the stack (or at your application layer boundaries). Use the Application.ThreadException event and the AppDomain.CurrentDomain.UnhandledException event and hook them up to event handlers in your Sub Main method.
Upvotes: 0
Reputation: 158369
It really depends on the function, but in general I would advice against having it display a MessageBox to the user; this is a task for the UI. If the function (for any valid reason) does show a MessageBox, provide an overload that is guaranteed to be "silent", so that a caller of the function can prevent the MessageBox. But, as I said, I think it's better to let the caller decide how to handle the exception. After all, it may be that the function is invoked from a Windows Service, where there is no UI.
I usually use one of these approaches:
This applies if the function itself cannot handle the exception. In some cases it may be that the function can handle the exceptional state and still perform its work. In these cases of course no exception will be thrown by the function.
Upvotes: 2
Reputation: 11637
I let all my errors bubble up to the top level, where i use an Application Error handler to handle them all.
If i have a specific error that i know can happen in a a function and that function can handle it, then i do.
Time-outs, object refs not set etc go up to the top handler.
Upvotes: 0