2

I was wondering if there is some compiler parameter, preferably in gcc (g++) which treats the lack of try/catch blocks as errors. This is the standard behavior in java and I was alway fond of it.

2
  • 2
    Nope, and it's basically not possible given the design of the standard, since it's not possible at compile time to know exactly what functions are going to be called. Commented Nov 30, 2009 at 14:38
  • 1
    Locate main function. Put everything in a try-catch block. No error. :) (I wonder what happens if exceptions are thrown during the construction of globals?)
    – UncleBens
    Commented Nov 30, 2009 at 15:54

3 Answers 3

8

Since checked exceptions in Java rely on the throw signature, you can read why you will not want to use throw function signatures in C++ in this question on SO.

1

Well, using exception specifications is generally a bad idea: http://cplusplus.co.il/2009/10/06/exception-specifications/

And if not using these, the compiler basically has no way of knowing which exception may be thrown, so there's no way to do that.

What you could do, is provide your own implementation of std::terminate (by invoking std::set_terminate()) and handle uncaught exceptions there.

0

One thing you can do in C++ with exceptions is use exception specifications on your functions. That doesn't actively prevent non-listed exceptions from being thrown from that function, but it makes them errors (and maps them all to the predefined unexpected().

So int f() throw (); is C++ for "treat any exception being raised from function f as an error".

1
  • 2
    Probably worth noting that it's "treat as runtime error". A C++ compiler is still required to compile void foo() throw() { throw 42; }. Commented Nov 30, 2009 at 19:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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