When to handle exceptions

I

iowna uass

Hi,

I'm converting a dll from VB6 to VS2008 and I have a question on when
exception handling should be used. The dll is a custom module that
integrates security into our corporate applications and is only used in our
environment.

The existing dll app uses err.raise to move the error up the stack.

My question is, do I need to use Try Catch blocks to handle exceptions? or
can if I write more robust code to deal with possible exception scenarios
(eg. use FileExist before trying to read file) and let the call stack trace
up to the app that is using the dll and handle it there?

I've been reading up on exception handling and MS recommends not to Throw
errors unless it's necessary. Something about using a lot of resources to do
this.
 
P

Phill W.

iowna uass wrote:

Question: "When to handle Exceptions"

Short Answer: When you can do something /useful/ when the Exception
happens.
My question is, do I need to use Try Catch blocks to handle exceptions?
Yes.

or can if I write more robust code to deal with possible exception
scenarios (eg. use FileExist before trying to read file)

You can, but there's still /no/ guarantee that everything you've checked
for will still work by the time you get around to actually /doing/
whatever it is. You're working in a multi-tasking operating system,
remember. In your example, your file might well exist when you test it,
but it may has "disappeared" by the time you subsequently try to open it
(or it might be "locked" and inaccessible, or lots of other problems
that you just can't code for).
and let the call stack trace up to the app that is using the dll
and handle it there?

The important question should be: "And do what?"

There are probably actions that you can (and should) take within the Dll
and you'll need Catch blocks to trap these. Given, you might then just
rethrow the Exception so that the client app knows there's a problem or
- more usefully - you might "handle" the exception, recover from the
problem and the client carries on in blissful ignorance that anything
untoward ever happened.
I've been reading up on exception handling and MS recommends not to Throw
errors unless it's necessary. Something about using a lot of resources to do
this.

Have you seen how many "first chance" exceptions get thrown when you're
debugging stuff in the IDE? Our Friends in Redmond may not "recommend"
it, but they do /plenty/ of it themselves.

It's part of the language; use it when it's sensible to do so.

HTH,
Phill W.
 
K

kimiraikkonen

iowna uass wrote:

Question: "When to handle Exceptions"

Short Answer: When you can do something /useful/ when the Exception
happens.


You can, but there's still /no/ guarantee that everything you've checked
for will still work by the time you get around to actually /doing/
whatever it is.  You're working in a multi-tasking operating system,
remember.  In your example, your file might well exist when you test it,
but it may has "disappeared" by the time you subsequently try to open it
(or it might be "locked" and inaccessible, or lots of other problems
that you just can't code for).


The important question should be: "And do what?"

There are probably actions that you can (and should) take within the Dll
and you'll need Catch blocks to trap these.  Given, you might then just
rethrow the Exception so that the client app knows there's a problem or
- more usefully - you might "handle" the exception, recover from the
problem and the client carries on in blissful ignorance that anything
untoward ever happened.


Have you seen how many "first chance" exceptions get thrown when you're
debugging stuff in the IDE?  Our Friends in Redmond may not "recommend"
it, but they do /plenty/ of it themselves.

It's part of the language; use it when it's sensible to do so.

HTH,
    Phill  W.

Use try-catch blocks as much as possible. Maybe you think you've
considered all the possibilities that can throw an exception, but you
may (and a normal human) have missed a point that create an exception
with no doubt. Catching an exception saves your time and consideration
hassle to solve the bug in your project. Remember Murphy's laws.
 
G

Guest

My question is, do I need to use Try Catch blocks to handle
exceptions? or can if I write more robust code to deal with possible
exception scenarios (eg. use FileExist before trying to read file) and
let the call stack trace up to the app that is using the dll and
handle it there?

Exceptions are just that - unexpected situations.

You should do as much upfront checking as possible, and then handle any
known exceptions (and unknown).
 
I

iowna uass

Short Answer: When you can do something /useful/ when the Exception
happens.

good answer. That pretty much sums up my predicament.

Maybe I should've elaborated. Our legacy systems (wow, I'm calling VB6
legacy) use a logging system that records exceptions on a local server, the
logs then get merged into a centralized database for analysis.
The dot net conversion will compliment that system using log 4 net. The
purpose of logging the exceptions are to identify issues and assist the
helpdesk in dealing with user problems. This will allow us to log specs for
app changes to fix code related exceptions. It also allows us to identify
network/database issues.
We want the error to "bubble up" to the app that is in use and then get
logged.

As for Try Catch blocks in dot net code, I'm using them where I don't want
or need the logging.
I'm more concerned with doing a Throw in the catch block just to move the
error along. I'm concerned I'd be losing stack trace info when I do that.

It's part of the language; use it when it's sensible to do so.

The sensible thing is what I'm having an issue with. How much is overkill?
 
A

amdrit

You seem to be attempting two serperate tasks here. The first is to manage
the application state with error handeling. The second is to record events
and application state in a log for review. I think if you attempt to
seperate the responsibilities out you will see a clearer path to your
solution.

Consider the windows event log and it's purpose. Record events of note for
later review. These events have one of five flags:

Information - Something has happened that does not affect the state of the
application, rather the user configuration has requested it to be noted
whenever it occurs.
Warning - Something that is potentially bad has or will happen as a result
of another condition.
Error - Something terrible has occured and the system has either worked
through the issue or it halted after creating the log entry.
Success Audit - Something that needed to be challenged prior to execution
has occured and the credentials were sufficient.
Failure Audit - Something that needed to be challenged prior to execution
has occured and the credentials were insufficient.

Also in the event log there are categories for the source of the issues and
a myriad of other data elements. Use of a logging system has little bearing
on defects, poor user experiences or other. It is simply a way to gather
information about user trends and potential enhancements for the future.

Not all exceptions are errors, simply oddities and do not affect the state
of the code. When you are catching exceptions, you should attempt to deal
with them and decide if the caller should be made aware of the situation.
The closer you get the user, the more important it is to determine when
there is a problem that the program cannot continue or something that can be
recorded in a log for later review.

Try blocks provide an opportunity for the developer to put in last ditch
logic before allowing the application to call it quits. The same held true
for VB6 with on error statements and lables, its just that with .Net it is
more streamlined and functionable.

Consider a method to commit data to the database

....

'Create log entry, outer process has begun

try
'Assuming that oCMD is a command and the command text is already set
dim intTries as integer=0
dim retry as boolean = false

'Create log entry, inner process has begun

do

try
oCMD.execute
retry = false
catch(e as oledbexception) 'Most specific type of exception
'Perhaps the error we caught was that the db was placed in single user
mode
'here we have an opportunity to think about the implications and next
steps
'We should probably retry this command a couple times before making a
stink about it
'Create log entry
intTries +=1
if intTries <= maxTries then retry = true
catch(e as applicationexception)'Less specific
'This is probably a specific case that we may or may not have
considered,
'Determine that and we decide what to do from there
'Create log entry
'set retry or throw exception
catch(e as exception) 'Bland exception
'This was totally unexpected here
'Create log entry
'Now throw a new exception
throw new ApplicationException("Inner Boom",e)
finally
'clean up your db objects
end try

if retry then
'Create log entry, we are attempting the inner process again
end if

loop while retry

'Success, create log entry

catch
'Here we caught something, perhaps it was from the inner try block
'we can just pass it along, the state of the application has been
compromised
throw new ApplicationException("Outer Boom",e)
finally
'perform remaining clean up here
end try

'Create outer process exit log entry

'return results here, if any
....
 
C

Cor Ligthert[MVP]

Iowna,

Use a catch in every situation where you can not check in another way
problems, but *never* in situations where you can check it, by instance if a
file exist (while you first have tried if the disk is running). However, you
should catch if somebody is removing a removable disk when you are busy or
an administrator closes a database server or even that it is not running at
all.

As well as you want to check by instance a date and time if is correct, feel
free to use it as well, because that is almost impossible to calculate,
while it is done for you. (This is build in with the IsDate).

Just my opinion,

Cor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top