Re: Catching Thrown Exceptions
On 02/20/2012 10:36 PM, Davej wrote:
I figured that if you threw an exception inside a try it would be
caught. No? In my Java program the throw was not caught. In C# this is
the way things work.
Could you show a code example?
Did your program have a 'catch' clause?
You need either a 'catch' or a 'finally' or both if you have a 'try', so I'm
guessing (absent your code) that you had a 'finally' or the code wouldn't have
compiled. I'm also guessing (absent your code) that you are trying to catch a
'RuntimeException', because a failure to catch a checked exception wouldn't
compile either. Ergo your code looks something like this (as I'm guessing,
absent your code):
try
{
somethingThatThrowsARuntimeException();
}
finally
{
whatever();
}
In such a case you'd add a 'catch' for the exception of interest. The catch
(pun intended) is that a runtime exception indicates a programming error.
Catching it should happen before code is released to the wild, that is to say,
you should code your program to make such a thing impossible. If you can
anticipate it enough to catch it, you can anticipate it enough to prevent it.
Band-aids stop bleeding, they don't cure colds. The right solution is to fix
the cause of a runtime exception, not to catch it.
That said, there's a notable exception (pun intended) to that rule. You can
throw runtime exceptions on purpose and catch them on purpose when it suits
you. You only do that as a guard against programming error, of course, not as
a substitute for correct programming, and thus to enforce invariants. One sure
sign that you're thinking correctly when catching runtime exceptions is that
'assert' conditions accompany the tossing thereof, or more correctly, confirm
that they've not been tossed.
Java is not C#. Like other computer languages it follows its own rules. It's
pointless to compare Java to any other language when trying to write a correct
Java program. So C# does that. Big frakkin' deal. So why aren't you using C#?
--
Lew
Honi soit qui mal y pense.
http://upload.wikimedia.org/wikipedia/commons/c/cf/Friz.jpg