1

Possible Duplicate:
How can I catch all types of exceptions in one catch block?

In C++ is there a way to catch ALL exceptions? If so, what would the syntax for that be?

Merci

Community
  • 1
  • 1
Nosrettap
  • 10,940
  • 23
  • 85
  • 140
  • You need to clarify; do you mean *all* exceptions or *all unhandled* exceptions ? After all, you could wrap your entry point in a try-catch block as Seth mentioned, but if there is inner code that explicitly handles the exception and lets the program continue, it won't hit your entry point catch block. – Russ Clarke Feb 27 '12 at 02:37
  • If you're doing this to debug an exception there is an easier way in Visual Studio; On the debug menu go to the Exceptions option and you can select options to VS stop when ever an exception occurs, even if it's handled, and a few other things. – Russ Clarke Feb 27 '12 at 02:39
  • And by the way, that's typically "poor form". Especially if you do something like `try { ... } catch (...) { ; }` (i.e. silently eat any/all possible exceptions). – paulsm4 Feb 27 '12 at 02:39

3 Answers3

8

Yes, you can catch all exceptions that were not handled (and not rethrown) by inner try/catch blocks by catching ...:

try {
    // do some stuff
} catch (...) {
    // catch any exceptions that weren't handled and/or rethrown in the try block
}

You can also combine this with other catches, but make sure they are above the catch (...) or they will be masked by the catch-all (and you should get a compiler error).

Seth Carnegie
  • 73,875
  • 22
  • 181
  • 249
5

You can catch all exceptions like this

try{
    // ...
} catch (...) {
    // ...
}

However a more useful thing to do is to catch specific exceptions and then finally fall to the (...)

try{
    // ...
} catch (const std::exception& ex) {
    // ...
} catch (const std::string& ex) {
    // ...
} catch (...) {
    // ...
}
1

No, you cannot catch ALL exceptions, because you cannot catch exceptions that have already been caught by another handler nested within your try/catch block.

nerozehl
  • 463
  • 1
  • 7
  • 19