How can I correctly implement a handler method for exceptions?

Suppose I have the following construct:

Public Sub SomeMethod() Try doSomething() Catch ex as Exception handleException(ex) End Try End Sub 

And I would like to write handleException (ex). Suppose my class has different event handling options:

  Public Enum ExceptionHandlingType DisplayInMessageBox 'Display in msgbox ThrowToCaller 'Raise the error to the caller routine RaiseOnMessageEvent 'e-mail End Enum 

Below I tried to write "handleException". It seems that no matter what I do, if the object was set in Exception "ThrowToCaller" mode, then the stack trace gets all messed up when I use handleException (). How can I just get a clean stack trace when the option is "ThrowToCaller" (every other option seems to work fine)

 Public Sub handleException(ex as Exception) Select Case mExceptionHandling Case ExceptionHandlingType.DisplayInMessageBox MsgBox(ex.Message) Case ExceptionHandlingType.ThrowToCaller Throw New Exception(ex.Message, ex) Case ExceptionHandlingType.RaiseOnMessageEvent SendEMailMessage(ex) End Select End Sub 
+4
source share
2 answers

Try changing the call to

 if (!HandleException(ex)) throw; 

and HandleException() before

 bool HandleException(Exception ex) { bool handled = false; if (ex is SomeException) { ... handle the exception ... handled = true } return handled; } 

That should do the trick.

+2
source

To save the exception stack trace in the catch block, you need to add it with the following syntax (in C #, not familiar with VB):

 try { // some operation ... } catch (Exception ex) { switch(mExceptionHandling) { case ExceptionHandlingType.ThrowToCaller: throw; case ExceptionHandlingType.DisplayInMessageBox: MsgBox(ex.Message); break; case ExceptionHandlingType.RaiseOnMessageEvent: SendEmailMessage(ex); break; default: throw; } } 

Take a look at the exception handling block block to get an idea of ​​the best exception handling methods.

EDIT: Look at the answers here to find ways to save the stack trace.

EDIT # 2 I think part of the problem here is that this is not the best way to handle exceptions for the case used. In appearance, it looks like a GUI code due to a message box. The decision to display a message box should be made outside of this particular catch block. One way is to use AOP to inject a message box handler for certain operations and certain types of exceptions. The catch-rethrow script is usually used when you want to throw an exception. At this point, you can get a workaround by extracting the stack trace using reflection, but consider refactoring your exception handling model in the future.

+2
source

All Articles