C++ – Why aren’t exceptions in C++ checked by the compiler

c++exceptionvisual-c++

C++ provides a syntax for checked exceptions, for example:

void G() throw(Exception);
void f() throw();

However, the Visual C++ compiler doesn't check them; the throw flag is simply ignored. In my opinion, this renders the exception feature unusable. So my question is: is there a way to make the compiler check whether exceptions are correctly caught/rethrown? For example a Visual C++ plugin or a different C++ compiler.

PS. I want the compiler to check whether exceptions are correctly caught, otherwise you end up in a situation where you have to put a catch around every single function call you make, even if they explicitly state they won't throw anything.

Update: the Visual C++ compiler does show a warning when throwing in a function marked with throw(). This is great, but regrettably, the warning doesn't show up when you call a subroutine that might throw. For example:

void f() throw(int) { throw int(13); }
void h() throw() { g(); } //no warning here!

Best Solution

What's funny is that Java has checked exceptions, and Java programmers hate those too.

Exception specifications in C++ are useless for 3 reasons:

1. C++ exception specifications inhibit optimization.

With the exception possibly of throw(), compilers insert extra code to check that when you throw an exception, it matches the exception specification of functions during a stack unwind. Way to make your program slower.

2. C++ exception specifications are not compiler-enforced

As far as your compiler is concerned, the following is syntactically correct:

void AStupidFunction() throw()
{
    throw 42;
}

What's worse, nothing useful happens if you violate an exception specification. Your program just terminates!

3. C++ exception specifications are part of a function's signature.

If you have a base class with a virtual function and try to override it, the exception specifications must match exactly. So, you'd better plan ahead, and it's still a pain.

struct A
{
    virtual int value() const throw() {return 10;}
}

struct B : public A
{
    virtual int value() const {return functionThatCanThrow();} // ERROR!
}

Exception specifications give you these problems, and the gain for using them is minimal. In contrast, if you avoid exception specifications altogether, coding is easier and you avoid this stuff.