I have a question about exceptions. I am under the impression that almost
ever method or group of methods should have try-call block(s).
That was Conventional Wisdom in VB6. Not so in .Net.
I am also under the impression that the 'last' final group of code
that is executed should have a final try-catch block.
Only if it needs one.
When I look some vb.net 2008 windows applications that some contractors
wrote at my job, I can not find any try-catch blocks. Would you think there
would be a reason for this?
It may be perfectly justified but, given the experiences I've had with
/some/ contractors, it could also be sheer laziness on their part. "If
it crashes, run it again" sort of thinking.
The Magic Word in Exception Handling is "Handling".
You add exception (/error) handling code where you can do some /good/,
i.e. where you can "handle" the strange circumstances that crop up in
your code from time to time.
It's best to do that as close to the cause of the problem as possible.
Say you have a method that reads the content of a file but the name of
that file is entered somewhere else by the User. This routine is the
best place to handle, say, FileNotFoundExceptions; you can pop up a
"File not Found - X" dialog, or pop up an OpenFileDialog and let them
pick the right file. If you let the Exception go any further afield,
though, you've lost that opportunity, that context within which you can
"fix" things. If you don't provide any Catch blocks at all
(<shudder/>), the run-time provides its own, which displays that awful,
generic "something nasty happened" dialog that you may be seeing in this
case.
Personally, I despair when people ask "how do I add a Global Exception
Handler to my program". That's so far from the cause of any problem
(actually, it's /just/ before the program curls up its toes and dies!)
that it's /far/ too late to do anything but log the problem to a file
for later - not that that's a Bad Idea as a backstop but it shouldn't be
your /only/ defence against dodgy data; imagine if MS Word stopped and
restarted itself every time you mis-spelled anything! ;-)
Is there a 'new way' for checking for errors? Do you think I may want
to over use try-catch blocks?
Whenever you catch yourself reaching for a Try..Catch (no pun intended),
think about these:
* Are you about to do something that /might/ fail?
* If it does fail, can you do anything to recover from that failure?
(and here, "recover" means getting your program back into a state as if
the problem had not happened).
If the answer to both of these is yes, you need a Try..Catch.
* Are you about to do something that you absolutely *must* "undo" before
you leave this method? (I'm thinking of thread synchronisation
constructs, here; Monitors, Mutexes and the like). If so, you probably
want a Finally block in there [as well].
HTH,
Phill W.