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

前端 未结 6 1689
广开言路
广开言路 2020-12-13 17:45

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

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

However, the Visual C++ compiler do

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-13 18:00

    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.

提交回复
热议问题