Error Handling Rollup to Main Procedure - vba

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?

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.

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.

Errors not locally handled will always* get trapped by the up-the-stack error handler if the error trapping option is set to "Break on Unhandled Errors". You'll find this setting in the IDE under Tools Options.
If it's set to "Break on All Errors", no error handler (neither local or up-the-stack) will be called. If it's set to "Break in Class Module", no out-of-class error handler will be called for in-class error.
Note that this option change the line on which the debugger stops: when an unhandled error occurs in a class module, the debugger stops on the line calling the class with "Break on Unhandled Errors" or on the offending line in the class with "Break in Class Module".
In Access, this option can be read programmatically with Application.GetOption("Error Trapping") and Application.SetOption("Error Trapping").
*As RBarryYoung has written, the most fatal errors (like stack overflow errors) won't be caught by any VBA error-handling.

Related

How do I find out what called my shared function

I have a function in vb.net that is shared. At one point it throws an error that says an 'open datareader already exists'. But this function is called from several different places in the program. How can I find out which part of the program called the function when it errors out?
You go to the Debug menu, show the Exceptions window, put a tick next to CLR exceptions and then run your program until it errors. As soon as the exception is raised VS will break, you will be able to see the call stack, and find out where the code was before. Note that this causes VS to stop on every exception, handled or not; it can become tedious to get to where you want to be - untick the "always break when this type of exception is thrown" in the exception helper if you just keep getting irrelevant exceptions breaking before this error you're trying to chase
It sounds like you're perhaps not creating/disposing of your DB access resources properly, especially if this is a static/shared context. Are you trying to reuse one DB connection? It wouldn't hurt to post the code of the faulting module

when it is correct purpose of exceptions

I am studying OOP, and I did not understood the concept of exception.
What are the correct uses of exceptions?
Why use exceptions when you already know a possible exception?
For example, I have seen a code sample where the programmer needed to access a file, and had an exception in case the file does not exist. Something like "catch(fileDoesNotExist e)".
Why not use an if to verify before take the action? And use exception only for not known issues, for logging or error messages.
The idea behind the concept of exception was to decouple the error handling code from the "normal" behaviour flow control. That lets to manage/handle the exception further up the call stack.
Historically, with structured language, error handling code (file opening error,...) was mixed within the "business" application code. It was also painful to improve the code in order to manage new error codes.
What are the correct uses of exceptions?
If it is not normal that your file doesn't exist or cannot be opened => it is considered as an exceptional situation => exception => exception handler
Why use exceptions when you already know a possible exception?
To decouple the business application code from the error handling. That eases source code readibility and maintenance.
Exception:
Exception is that interrupt(break) the normal flow of the program.It's thrown at runtime.
Exception Handling
Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL, Remote etc
In java there are mainly two types of exception that checked and unchecked.Other than Error is there
Hierarchy of Exception classes in Java
Why use exceptions when you already know a possible exception?
basically exception handling use to mainly,we assuming in that our particular code will occur some(NullPointerException,ArrayIndexOutOfBoundsException etc..)exception.If we not Handle that,program will break.Actually that Exception it may or may not will happen.But so we need to handle normal flow of the program it occurred or not.Otherwise after that particular code section not executing.

Preventing Exceptions without Stack Frames with Error Exception Handler and Shutdown Sequences

I've run over a somewhat little problem over the week. The error message upfront this is about:
[30-Dec-2012 15:19:32] PHP Fatal error: Exception thrown without a stack frame in Unknown on line 0
I think it is because my error handler (see below for details) is turning any error into an exception. I might should prevent that in case there is no stack frame.
Is there an easy way to find out if there is any stack frame or not in PHP?
Details:
On one of my websites I've got an error handler running that is turning every error into an exception, the common ErrorException to be precise.
I introduced it some time ago because the site is mainly legacy code and I wanted to have any issue result in an exception I can finally "catch" in a streamlined fashion an exception handler and give the request a stop.
I put this into class of it's own, the handler is registered and also in parallel an output buffer is opened to catch the output up until the exception is thrown. Basically code like this:
// register output buffering
$r = ob_start(array($this, 'handleBuffer'));
// register error handler
$this->_originalErrorHandler = set_error_handler(array($this, 'handleError'));
// register exception handler
$this->_originalExceptionHandler = set_exception_handler(array($this, 'handleException'));
This worked all fine and dandy until I decided to add another output buffering class into the mix. Just one that catches as well all output and then can do some "post production" on the website, including checking for HTML problems (yes, it's all a bit legacy so actually this is a bit duck-taped, I know). That also worked very fine btw. however not when I made a mistake in the new component:
[30-Dec-2012 15:19:32] PHP Fatal error: Exception thrown without a stack frame in Unknown on line 0
This is basically my problem. Is there an easy way to prevent getting these errors? I somewhat know why the error is given but I'm not so entirely sure so it's hard for me to really circumvent the problem. I tried to release the new output buffer before the script enters the new shutdown phase because I thought this would cause this. But this didn't make it.
Your problem indicates that you are using an EOL (End Of Life) version of PHP (specifically PHP < 5.3.0), which means it's no longer supported. This issue comes from throwing an exception where no strack frame exists and as such the old engine did not know how to handle those exceptions properly.
This can be due to a couple of different reasons. Some of the most common ones are as follows:
You threw an exception from inside an error handler or exception handler.
You threw an exception from inside a destructor.
You threw an exception from inside a callback (like an output buffering callback function).
Here's an example that demonstrates your problem under some of those circumstances...
function myErrorHandler($errno, $errstr, $errfile, $errline)
{
throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
function myExceptionHandler($exception) {
echo "We got an exception with message: '{$exception->getMessage()}'";
}
function myCallBack($contents) {
trigger_error('ohnoes!'); // You can't throw an error from the output buffer callback function in older versions of PHP < 5.3
}
class Foo {
public function __destruct() {
trigger_error('ohnoes!'); // You can't throw an error from a destructor in older versions of PHP < 5.3
}
}
set_error_handler('myErrorHandler');
set_exception_handler('myExceptionHandler');
The above code would cause you to see the fatal error you described here...
ob_start("myCallBack");
... and here...
$foo = new foo;
This problem has been fixed in PHP >= 5.3.0 so you should not see this issue if you were using the most current version of PHP.
The simplest fix is to upgrade your PHP. If that is not an option you must consider these facts that you can not throw exceptions where PHP does not expect them to be thrown (in callback functions, error handlers, exceptions handlers, etc... -- which are actually all considered to be callbacks to PHP).
The other thing is you should not be turning every error into an exception in this way. If what you are doing is as the code I supplied demonstrates (i.e. throwing an exception from inside the error handler -- thus turning every error into an exception) then you are going to cause yourself a lot of pain and with virtually no benefit. PHP errors are not meant to be handled. They are meant to inform the client of a problem (the client being the person writing the PHP code), or potential problem. Handling the error itself is not as simple as turning every error into an exception and then handling that exception, because not every error should be exceptional. For instance, E_NOTICE level errors have no place in exception handling. They are primarily used to notify you of a potential for a bug, not that there is necessarily something buggy with your code and not to mention that most of them can't even be handled easily in user-space code (they mostly require re-factoring the code itself). I strongly advice against this poor practice.

How to debug exception on other thread?

I have a lot of shortlived threads that updates my program, by events fired from a socket connection. My problem is I don't know how to debug this, like how to get the proper information on where in the code the exceptions occur. Because I get for example an exception like below, and this will just be the print in the Immidiate Window. There is no pop-up window, and it does not highlight any line in the code or show even what method it was in.
What am I missing? What I can do to see these things? And what improvements does VS2010 give on this situation, if any?
A first chance exception of type 'System.InvalidOperationException' occurred in System.Core.dll
A first chance exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll
A first chance exception of type 'System.Threading.ThreadAbortException' occurred in Krs.Ats.IBNet.dll
Go to "Debug -> Exceptions...", locate the "Common Language Runtime Exceptions" and check the "Thrown" mark. Now start debugging your application. Once any of CLR exception occurs the execution will stop on that line.

A First Chance Exception

've been running through the MSDN help documents to get a hang of Visual Basic. After trying out the example using timers --one drags a label and timer component into the designer and adds the following to the components subroutine
Label1.Text = My.Computer.Clock.LocalTime.ToLongTimeString
The output for the immediate window during debug is the following
A first chance exception of type
'System.InvalidCastException' occured
in Microsoft.VisualBasic.dll
A first
chance exception of type
'System.InvalidCastException' occured
in Microsoft.VisualBasic.dll
The same error occurs on a previous MSDN example using a context menu component. Should I Try...Catch...Finally this error and try to move on? Or, am I dealing with something much more serious?
When you see something about a first chance exception, it only means that an exception was caught within the code you called but does not necessarily mean that the code failed. If the code runs without causing your program to crash and returns a valid value, then do not have a problem. You will also see output in the debug window about first chance exceptions when you implement your own try/catch blocks.
In the Debug menu -> Exceptions, you can enable the debugger to stop when an Exception is first thrown, even if it would be caught later; if you want to find out what's happening, this is the easiest way to do it
In the first chance exception examine the details of the exception. You should see a stack frame/trace property. In there you should see what line the error occurs on. This should help you.
In the IDE try going to Tools > Options > Projects and Solutions > VB Defaults and setting Option Strict to 'On' - this may help catch casting problems when you compile your project rather than when you run it.
A 'first chance execption' does not necessarily mean you have a problem in your code. It could mean the IDE or the compiler or any other involved component encountered and handled an error and in the process the debugger is notified and the exception is being reported to the immediate window. This is an excellent post on the topic:
http://blogs.msdn.com/davidklinems/archive/2005/07/12/438061.aspx
A quick and easy solution for debug and diag of First Chance Exception is :
AppDomain.CurrentDomain.FirstChanceException += CurrentDomainOnFirstChanceException;
and then
private void CurrentDomainOnFirstChanceException(object sender, FirstChanceExceptionEventArgs firstChanceExceptionEventArgs)
{
if (firstChanceExceptionEventArgs.Exception is NullReferenceException)
{
// do your handling and debugging :)
}
}
Multiple First Chance Exception during the runtime can cripple the performance of your application because exception handling is expensive. Especially in web apps. You can add this handler and look at specific first chance exceptions and try to avoid/correct them.