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

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)