Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

My company head says that I must write all , i.e. ALL my code within Try-catch statements. Now, I can understand the 'better be safe than sorry' approach here, but isn't it too chicken-hearted to think that there will be an exception when the Labels are created, form's position is set. has there been instances where Exceptions in Such simple operations.

share|improve this question
4  
This sounds like buzz terms by the same people that say that all SQL should be written as stored procedures for better performance. –  sunpech Aug 2 '11 at 12:40
4  
Would you prefer, "If your code creates a run-time-error, you're fired." The game of chicken is fun until you see your opponent toss the steering wheel and brake pedal out the window. –  JeffO Aug 2 '11 at 12:53
3  
@Jeff O - I actually believe that in software development the opponent is a freight train. –  Joris Timmermans Aug 2 '11 at 13:03
4  
The best expression I've heard for this style of exception handling is "Nailing the corpse in the upright position", meaning, it leaves the application in an unexpected state. Fail Fast, Fail Loudly is a much more modern approach, so you can actually work all the bugs out. –  Brook Aug 2 '11 at 13:12
2  
The subject of the request is irrelevant... just saying "my company head says I should code..." is a big red flag. It is micromanagement... this is not his job. –  JoelFan Aug 2 '11 at 14:53
show 10 more comments

6 Answers

up vote 12 down vote accepted

My company head says that I must write all, i.e. ALL my code within Try-catch statements.

Well, this is a little overdone and just leads to noisy code. What are the benefits of having all the code (each method e.g.) written with a try catch handler? It just tells you there's an error to be fixed in most of the cases. Often times, the exception can and should be avoided in the first place.

A look on the stack trace is mostly sufficient to reveal the cause in your code, even if the faulting method does not perform the catch itself. There're times when developers corrupt stack-traces in exceptions, but that's far more often the case when you have lots and lots of exception handlers. Like anything: A little is good, but too much of it is poison.

Exception handling is indeed pretty simple:

Catch Exceptions

  • whenever you need a special action as a reaction to the exception
  • whenever an exception would leave the program in an inconsistent state if unhandled

If you think about it, then there's most always just one place which is good to handle an occuring exception. And thus the handler should be in that place.

Many exceptions shouldn't even be thrown in the first place, so don't build your control structures around exception handling, rather try to avoid the possible occurence of exceptions whenever and wherever possible.

Remember to crash early when things go (unrepairably) wrong. Putting all the code in try-catch statements is absurd, but don't forget to report and log ALL exceptions.

share|improve this answer
    
+1 Not only leads this to noisy code, but even worse performance. When you put statements in a try block, the HotSpot Compiler won't be able to apply optimisations he otherwise would do. –  Oliver Weiler Aug 2 '11 at 14:42
    
@Oliver Weiler: Do you have a citation that explains what optimizations the HotSpot compiler doesn't do in try/catch blocks? –  Kaypro II Aug 2 '11 at 21:35
add comment

I personally can't stand exceptions, they are VERY, VERY, VERY hard to handle correctly. And trying to uncorrupt the corrupt data is VERY, VERY, VERY hard!

http://blogs.msdn.com/b/mgrier/archive/2004/02/18/75324.aspx

http://blogs.msdn.com/b/oldnewthing/archive/2004/04/22/118161.aspx

http://blogs.msdn.com/b/oldnewthing/archive/2005/01/14/352949.aspx

http://www.joelonsoftware.com/items/2003/10/13.html

If you don't call every function like:

try
{
    TrivialFunction();
}
catch(TypeAException)
{
    //MaybeFix
}
catch(TypeBException)
{
    //MaybeFix
}
catch(TypeCException)
{
    //NO FIX - CORRUPT DATA
}
catch(TypeDException)
{
    //NO FIX - UNKNOWN STATE
}
catch(OutOfMemoryException)
{
    //Try to fix this one! Destructors might allocate on their own ;)
}
catch(Exception)
{
    //Nothing to see here, move on, everything is OK ;)
}

There is no way you'll clean up correctly on every exit point. Exceptions are HARD!

The only good thing about exceptions is that if you don't catch them, the app crashes on unexpected behavior.

share|improve this answer
add comment

You should use try-catch when appropriate, but please oh please don't catch all exceptions and not even log it. At that point it's code smell and shoddy work.

share|improve this answer
1  
+1 for logging. Programs in the wild are black boxes. When they fail, a log saying "Here's what happened" goes a very long way to solving the problem. I've had errors in my programs that went unreported, and they were uncovered only after I found them in the log. –  Andrew Neely Aug 2 '11 at 14:02
add comment

Overall, using try/catch that much is deprecated, because catch block is so expensive from the point of resources. Try/catch usage reminds me of risk management. Risk management has two dimensions:

  1. The probability of risk happening
  2. The damage it can have

Now, if you go out of your house, a piano falling on your head somewhere while is so unlikelihood to happen (maybe 0.001%), but can kill you.

Exception handling is like that. Try block is not expensive. But catch block is really expensive, because it needs to create a table of stack trace, and doing other stuff. Therefore in making a decision about try/catch blocks, you should consider how many times you probably hit catch block. If among 10,000 usages, you only hit it 1 time, then use it. But if it's a form, and the user probably doesn't fill it correctly 50% times, then you should avoid putting a try/catch block into action there.

In places where the probability of exception occurrence is high, it's recommended to use if {} else {} blocks to avoid exception occurrence. For example, where you want to divide two numbers, instead of writing:

try
{
    int result = a/b;
}
catch (DivisionByZeroException ex)
{
    // Showing a message here, and logging of course.
}

you should write:

if (b == 0)
{
    int result = a/b;
}
else
{
    // Showing a message to user to change the value of b, etc.
}
share|improve this answer
1  
+1 for using if/else to deal with "exceptions" that are basically just application logic. –  Morgan Herlocker Aug 2 '11 at 13:14
    
If it's user-related, remember that computers are massively faster than people. An exception thrown in 50% of form submissions is still only likely to happen a few times a second even with many users. –  Donal Fellows Aug 2 '11 at 13:53
1  
I don't agree with you on the avoidance of try/catch blocks. Constantly trying to anticipate exceptions is error prone, expensive in developer time, and makes your code harder to read. A loop that throws a million exceptions and catches them takes 500ms to run on my machine (vs. 1ms for an empty loop), which is not real-world performance difference in 99.99% of cases (and all UI code). You should use exceptions except in cases where you know the performance penalty matters, because they make your code more reliable and let you assume that the previous code executed successfully. –  Kaypro II Aug 2 '11 at 21:14
    
@cosmic.osmo, do you retrieve the stacktrace or just catch it? –  user1249 Jan 4 '12 at 15:36
add comment

I would turn this the other way around. Yes, as a general rule exception handling is a good thing, but can you actually handle every possible exception in a sensible manner at the point where it is caught? Sometimes, particularly if you are not writing mission-critical software, it is better to simply crash and burn in some half-way-controlled manner when things go horribly wrong.

If you cannot be 100% certain that you can handle every single exception that might possibly be caught, you are probably better off writing some sort of general exception handler, wrapping the program's main loop in it - the exact mechanics of how to do that obviously depends on what language you are working in. There, log as much detail about the exception as you can, save program state (somewhere other than to whatever data store the user is currently working against - remember, it may all be corrupted at this point), and so on. Then, rethrow the exception and let the OS handle it however it sees fit. In this catch-all exception handler, be prepared for catastrophic failure. Then, when the program is restarted, look to see if this state is in any way useful, and restore what can be salvaged if it is; and possibly offer the user to send a bug report back to you.

share|improve this answer
4  
+1: Never catch an exception if you can't immediately deal with it correctly. (Alas, sometimes you have to trap it just to let it roam free again but tagged as a different type, as part of API coercing: I hate that.) –  Donal Fellows Aug 2 '11 at 13:55
add comment

but isn't it too chicken-hearted to think that there will be an exception when the Labels are created, form's position is set. has there been instances where Exceptions in Such simple operations.

Absolutely yes! There's always a way for things to go wrong that you didn't foresee. And "chicken-hearted" is a ridiculous expression to use in this context; software development is not about proving your machismo through ignoring potential problems.

What is a valid question is whether it's useful for exceptions to be caught at the point where your coding standards say they have to. Your statement reads like you have to have try/catch block around every method body, and that is indeed absurd because you often cannot immediately do something useful with an exception, and that's actually the whole point of exceptions: that you can choose to let them propagate up the call stack to be dealt with at the appropriate point.

share|improve this answer
13  
My apps know better than to throw exceptions or they'll get the beating of their life. Once they think you're chicken-hearted, they'll crash all over you. –  JeffO Aug 2 '11 at 12:08
    
@Michael Borgwardt: hehe, so you downvoted me. You downvoted on this question and the only downvote is on my post. You seem to have a serious problem with your ego or your self-esteem. I noticed that on other quetsions, too. You know, other programmers have good answers, too. –  Falcon Aug 2 '11 at 16:52
    
@Falcon: I did not downvote anything on this question. I have no idea what leads you to believe otherwise, but if anyone has a serious ego problem, it is you. –  Michael Borgwardt Aug 2 '11 at 20:37
    
@Michael Borwardt: Maybe I am wrong. In that case I apologize. It could be that's just the downvote on your own question that caused me to think that you downvoted here. Sorry. –  Falcon Aug 3 '11 at 6:03
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.