Friday, March 23, 2012

FYI: Using Try's with Finally

Within my script component I was having some difficulty getting nested Exceptions to bubble out of the script component logic. The symptom appears when you get an ex.message of "Object reference not set to an instance of an object." As soon as I removed the Finally section my message (or the actual Exception object) was properly passed to the caller.

I've only done minimal work with Try/Catch/Finally structures. Is this normal?

Thanks,

Jeff Tolman
E&M Electric

Sounds like you are "swallowing" the exception. Catching it and then not doing anything with it. A code sample would be helpful.|||

Hey Jason,

No, I'm always passing on the exception. The problem comes when there is a Finally section after the Catch. The message that I throw up to the caller does not make it and shows up as the "Object reference not set to an instance of an object" message. It works fine without the Finally clause.

Jeff

|||

JazzGeek wrote:

The problem comes when there is a Finally section after the Catch. The message that I throw up to the caller does not make it and shows up as the "Object reference not set to an instance of an object" message.

I suspect the code inside Finally block fails (probably due to uninitialized variable) and throws a new exception. Could you post the code? Check that all the variables that code inside Finally uses has been assigned some objects, even if an exception is thrown before this code.

|||

I only had one line of code within the Finally block:

....
Catch ex as Exception
Throw ex
Finally
sqlReader.Close()
End Try

I ended up doing this:

....
Catch ex as Exception
Throw ex
End Try
sqlReader.Close()

which worked.

Jeff

|||

Is the sqlReader variable initialized? Most likely, when the first exception occurs, sqlReader is not assigned anything. So when you try to close null object, you get the new "Object reference not set to an instance of an object" exception, and this exception is propagated up instead of the original. If sqlReader.Close() is out of the finally scope, it is not called when first exception is thrown.

I don't think there is anything specific to SSIS here. Finally could be used in SSIS script component, but as anywhere, you should be careful to avoid throwing new exceptions inside catch or finally blocks, otherwise this new exception is propagated to next level, instead of original which is lost.

No comments:

Post a Comment