views:

1430

answers:

16

First of all, I'm not trying to be critical of anyone here or saying that all .Net programmers are this way. But I'm definitely noticing a trend: .Net programmers seem to avoid exceptions like they're the plague.

Of course, there's always the Raymond Chen blog post about how hard exceptions can be to handle. But that doesn't just apply to .Net.

In a lot of other languages/environments, I don't notice that programmers are as likely to avoid exceptions as they are in .Net. Heck, in Python, exceptions are thrown in normal program execution (iterators throw StopIteration exceptions).

So what am I missing here? Or am I totally off base in thinking that .net programmers avoid exceptions more than others?

+24  A: 

Performance is the fear monger's buzzword when it comes to exceptions - but that really only applies to throwing them or handling them in tight loops, or for when relying on them for control flow. Personally I see exceptions as another tool in my toolbox; I'm not scared of them at all. Ideally when you use exceptions you're using them in exceptional circumstances - that is, should no longer be concerned with performance, but rather with fixing the problem (rare) or failing fast and notifying the user / logging / etc.

Edit: JaredPar mentioned a great quote regarding this that I feel is important enough to repeat: "If you're worried about Exception performance, you're using them incorrectly." Once we find attribution I'll amend this post to include it.

Erik Forbes
My favorite quote is "if you're worried about Exception performance, you're using them incorrectly"
JaredPar
Yes - exactly. :) Great way to counter Exception fear.
Erik Forbes
@JaredPar - I like it.
Jason Baker
@JaredPar - is there a particular book or article that quote is from?
Michael Burr
I always had the idea that Java was designed with more of an eye towards theoretical purity (with a big exception to primitive types!), and .NET was designed more for a practical programmer
mcjabberz
+13  A: 

Under .NET, exceptions are (can be) expensive operations. Most .NET developers prefer to code around possible exceptions.

For example it's better to check for null rather than catch NullExceptions.

Guideline here and here

KiwiBastard
Catching a NullReferenceException is almost always a sign of a bug.
JaredPar
Exceptions should only catch exceptional events. Generally checking if something is null when there is a fair chance it will be is not an exceptional circumstance and should not be done with exceptions.
Craig
+1 Craig - exactly.
Erik Forbes
+5  A: 

Using exceptions is okay in some situations, but exception handling in .Net is incredibly slow. So using exceptions for control flow is nearly always a mistake, if a simple IF statement will do the job just well.

Short Answer: performance

PaulMorel
nearly always a mistake? I'd say using exceptions for control flow is ALWAYS a mistake
lomaxx
Exceptions are not designed for control flow. Anyone who uses them for this doesn't understand exceptions.
Craig
Yes, you are both correct. Still, many beginners DO use exceptions in place of IF statements, simply because they don't know any better.
PaulMorel
+1  A: 

I work in a Java / .NET shop and neither group avoids exceptions as a general rule.

They are just another tool and definitely have their place when used correctly.

nzpcmad
A: 

Wild guess: could it be the fact that a lot of .NET programmers come from other languages where exceptions are tolerated much less?

I mostly program in C# (and a little and Java) and see no problems with exceptions as long as they are handled carefully (just like EVERYTHING else should be).

MK_Dev
+14  A: 

.NET is heavily optimized to allow the non-exceptional case to run as fast as possible, at the expense of exception performance.

Comparing IronPython to CPython

The only two tests that really stand out as showing a deep performance issue are the two exception handling ones. These are the only tests where either implementation is more than 4x faster than the other. IronPython is 10x faster on the try/catch without an exception and CPython is 30x faster when an exception is actually raised. This is a deliberate design decision within .NET to make code that doesn't throw exceptions run faster - even if that means slowing down code that does throw exceptions. I'm fairly confident this was the right decision - and even remember the day long ago when Guido was discussing Python's exception system and explained that he'd accept almost any slow-down to the exceptional case in return for removing a single instruction from the non-exceptional path.

Jimmy
That's interesting. I'd never realized that.
Jason Baker
I'm accepting this because it explains the issue so well in a way I hadn't thought of.
Jason Baker
But it doesn't answer the question. I don't think there are enough people who even know about this to affect the general population of developers. Besides which it's a great example of optimization too early.
le dorfier
+2  A: 

The performance issue is a good point. The performance of exceptions in .NET 1.0 was really bad especially. However, I'd say that another reason is due to pre VB.NET - in the old days of Visual Basic the only way to handle errors/exceptions was unstructured goto , resume & resume next. This made most VB programmers avoid errors/exceptions at all costs. Old habits die hard. A lot C# programmers used to be VB programmers, though they might not want to admit it. I, for one loves my VB.NET.

Booji Boy
+2  A: 

Throwing exceptions during "normal" program execution ruins the debugging experience ("catch all first-chance exceptions" is very handy, except in code that throws lots of exceptions as part of main-line execution).

The design guidelines are good.

Brian
+1  A: 

I remember back then in .NET 1.1 when a exception tool like 3 seconds to be raised. Everything went fast but when the exception was thrown it took forever. So I started to avoid them :)

Tigraine
+2  A: 

Using exceptions as another control flow mechanism (i.e. as default unstructured GOTO command) should be expensive and discouraged.

Using exceptions as:

  • application layer firewalls - to keep the app from blundering on after a business logic failure and writing corrupt info to a database for instance
  • and contract enforcers - when you invoke a method your contract with that method stipulates parameter and state will be consonant with the service you request that method provide

this doesn't require performance so much as a reliable mechanism for capturing and managing an app failure

kloucks
+5  A: 

Single biggest reason: VB6 didn't have them.

le dorfier
MusiGenesis
Yup, "On Error". Which doesn't map to "Try .. Catch .." and there's no alternative for going back.
le dorfier
No, "On Error Resume Next" followed by the problematic line followed by "If Err <> 0 Then {whatever} End If" maps to "try ... catch". This is how On Error Resume Next was supposed to be used, not as a blanket let-crappy-code-keep-executing technique like it was used 99% of the time.
MusiGenesis
And as every tutorial or sample code I ever saw on MSDN showed it, too. I've seen no evidence that anyone as Microsoft knew it was supposed to be used that way. Do you remember any counterexamples?
le dorfier
You guys are reminding me of all those classic ASP sites I had to maintain. Bad stackers, bad!
Jason Baker
@doofle: most of my VB neurons are dead and gone, sorry. Replace "was supposed to be used" with "should have been used".
MusiGenesis
+2  A: 

Programmers don't use exceptions because they think their code will never throw them. Programmers don't tend to see bugs or problems as when they write their code and test it locally, everything works. So why do you need exceptions? Thinking about what will or won't throw an exception interrupts your main stream of thought.

Petras
+8  A: 

Depends what you mean by "avoid exceptions". You might mean
1. design your APIs so that incorrect arguments are indicated by return codes, not exceptions
2. Not establish any exception handlers (e.g. try/catch, or begin/rescue)
3. take extra care in checking arguments, so as not to cause exceptions in functions called.

Or perhaps you meant something else entirely.

As others above already said, it's costly to raise an exception. But more than that, it can be unclear, and I would avoid unclear code even more than I would avoid costly code.

Exceptions should be used for exceptional (that is, unusual or unacceptable situtations.) So for instance, if one were writing a string search function that returns the 0-based index of the first matching substring, what would you do if the string is not found. You could raise an exception or you could return -1. All things being equal, -1 is better, as failing to find a string within another is non unacceptable or even wrong. On the other hand, if you were writing a validation function, let's say it's something that's supposed to check that the user has entered a valid ice-cream flavour (and in your limited world, there are only three flavours) then it might be right to throw (or raise) an Exception if given an invalid kind of ice-cream. (But then again, suppose you want the application, if given an "invalid" ice-cream, to put up a form to place a special order for the ice-cream. Then you would not want the exception, you'd want the return code.

As for not establishing any handlers, one thing I can tell you is I have seen a lot of code that has empty (omnivorous) error handlers that just silently ignore the exception and keep going. I don't know whether .NET people do that any more than on other platforms, but it drives me nuts, as it makes debugging quite difficult.)

Jim Davis
A: 

Not to diss anyone here, but I think that .NET is so easy for inexperienced programmers to use that you will see a lot of strange .NET code.

I have several friends who I studied with who never ever should be programming professionals with the limited skillset they had at graduation.

Nailer
+2  A: 

Exceptions should be used for things are truly exceptional. If you can check to see if a file exists before you open it and handle it that way then it is what you should do. There is no good way to determine that you're out of memory on a system until you try to allocate something and an exception should be generated. Of course if you receive an OutOfMemoryException there is nothing your application can do other than clean up the state it is in as best it can and gracefully shut down. Like many others have said the performance for exceptions in the early version of .Net was pretty bad. I don't know for sure if the new version has improved because I try to handle exceptions a bit differently these days.

There are some cases where you truly can do something about the exception and these are the only exceptions your application should capture. I hate seeing a catch (Exception) {} block because there might be a legitimate exception being gobbled up by the catch block that should otherwise cause the application to terminate.

Eric Lippert has good things to say about exceptions and handling them:

http://blogs.msdn.com/ericlippert/archive/2008/09/10/vexing-exceptions.aspx

Steven Behnke
+1  A: 

I cannot comment yet, but in response to the Java comment here's Anders' point of view on checked exceptions and why the exception handling system was designed the way it was:

http://www.artima.com/intv/handcuffs.html

Steven Behnke