views:

275

answers:

2
+2  Q: 

VBA Error Handling

If I have a main procedure with error handling that calls other procedures without error handling, should errors roll up to the main procedure?

What if the procedures without error handling use functions without error handling?

Should everything roll up to the main procedure's error handling?

I apologize ahead of time if this is a stupid questions.

Thanks for any help, comments, etc.

+5  A: 

Yes, unhandled errors will roll up the stack. If you have no error-handling in your main routine (or in the current event-handling routine), then the error will roll up to VBA itself, which will either cause your program to abort, or reset the VBA environment within the host applicaton. (you don't want that).


I can think of two apparent exceptions to this: one illusory and one real:

1) If VBA is entered through an unanticipated event-path, instead of though the main routine, it may appear that your Main-routines error-handler is being bypassed by the error-return, but in reality, it's another thread, so when it rolls-up from an event-handler, it goes to VBA independently of your Main routine's main-thread.

2) The VBA error-handling cannot catch ALL errors, in particular, most FATAL errors cannot be caught by it and crash (and reset) the whole VBA environment. "Stack Overflow" errors are an example.

RBarryYoung
Thanks for the reply. That's what I thought, and that seems to be the case 99% of the time. But every once in a while, a function will have an error, and instead of rolling up, I get the VBA error window (with debug, etc.). I don't understand why.
I would need a more specific example to comment further.
RBarryYoung
Ooo! +1 for added explanations ("2 apparent exceptions").
Smandoli
+2  A: 

Procedure A with error-handling will catch all errors. Procedure B with no error-handling will catch none.

If A calls B and B has an error, it will roll up and be caught in A's handler.
If B calls A and B has an error, there won't be any handling.
If B calls A and A has an error, A will catch it.

Whether it's a function or a procedure makes no difference. However it's worth noting that a class module won't handle errors locally, but passes them back up the stack to the first non-class module.

I'm not sure what you mean by "should," but where you want an error caught can depend on what you want to do with the error. For example, if a certain error requires you to make a small tweak on a string and then resume where you were, then you want very local handling. In other cases, simplicity might call for top-level handling.

Smandoli
If you're having weird behavior, it might be good to post the weirded code (with its err-handling parts of course) and cite which errors are not being handled rightly.
Smandoli