2

Possible Duplicate:
When and how should I use exception handling?

I have seen that programmer have "try{}catch(){}" block written in each method both in C# and C++. In C# it seems usual. But in C++ it seems obscure. What is the right way to use them?

Community
  • 1
  • 1

2 Answers2

10

There are really only three times you should be using try/catch:

  1. At the top level of your application so you can present a friendly error message to your user (and hopefully log some useful information so you can fix the problem later).

  2. When you can properly recover from the Exception (or at least clean up resources that are no longer needed).

  3. When you're going to do something with the Exception information and then bubble the Exception up.

Other than those three situations, there's no reason to use a try/catch block. You should just let the Exception bubble up to the caller so they can handle it if need be.

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
  • You also need to bear in mind that throwing exceptions is an expensive process, so throwing unnecessary exceptions should be avoided. – Liam Oct 19 '12 at 15:55
  • 3
    In Java (and to and extent C# but mitigated with using) catching exceptions is also used for non memory resource management before allowing the exception to propagate up (this is not required in C++ because of RAII) – Martin York Oct 19 '12 at 15:57
6

The intention of exceptions it that handling should be deferred to a point where something useful can be done, whether that's notifying the user, re-trying, or whatever. So, catching exceptions in every function is generally poor design.

As Justin says, you may need to catch and re-throw an exception to do local cleanup - this would explain the C# code.

In C++ the idiomatic approach is RAII, which instead uses deterministic destruction to perform the local cleanup, and avoids catch handlers that don't-really-handle-but-just-re-throw.

Useless
  • 64,155
  • 6
  • 88
  • 132