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.
-
2Nope, 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.– Dominic RodgerCommented Nov 30, 2009 at 14:38
-
1Locate main function. Put everything in a try-catch block. No error. :) (I wonder what happens if exceptions are thrown during the construction of globals?)– UncleBensCommented Nov 30, 2009 at 15:54
3 Answers
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.
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.
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".
-
2Probably 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