What can (and what cannot) throw an exception in C ++?

Is there a complete list (possibly recursively defined) from the "code instructions" that could lead to an exception in C ++? Something like that:

1) throw(naturally)

2) causes new

3) calls any functions from the standard library that are documented so that they can be dropped.

4) calls any user-defined functions (including constructors) that contain operations from 1-3.

5) Something else? Highlighting local objects on the stack, operations with built-in types, dereference pointers, titration - can they throw?

6) Everything else is an exception.

Without exception, I do not mean operations that are always successful. Of course, dereferencing a pointer is not. But still, it makes no sense to wrap it in a block try-catch, think about the exception-safety of the function of dereferencing a pointer, etc. Thus, code that is either successful or leads to undefined can be considered an exception.

Update. Despite my last paragraph, I still get a comment that might cause undefined behavior, so let me explain what I mean. Consider the following code:

void bar();
Class C{
...
public:
  foo() {
    something_that_breaks_class_invariants;
    bar();
    something_that_restores_class_invariants;
  }
}

, , , bar() , . bar() try-catch , .

bar() , undefined ( , , - ), foo() . foo() undefined bar(). bar() , noexcept ..

, : bar(), - ?

+4
3

, , ++, .

  • throw
  • new bad_alloc
  • dynamic_cast bad_cast
  • typeid bad_typeid
  • , noexcept throw()

++: default/copy/move, , ( , noexcept) .

- , noexcept, , .

0

. , : dynamic_cast<Derived&>. , . dynamic_cast<Derived*> .

. , , . .

"Undefined Behavior" - . ++ Undefined , , UB. , UB, ++.

0

: , , , , . :

template <class T> T foo(const T& arg) { return arg; }    //can throw (copy constructor!)
template <class T> void foo(T a, T b) { a+b; }    //can throw (+ is overloadable)

template <class T>
void foo(T iter, T end) {
    for(; iter < end; iter++) {    //both the < and the ++ operator can throw
        iter->bar();    //even the -> operator is overloadable and can throw
    }
}

In short, whenever you have no knowledge of the types involved, as is usually the case with templates, you should pretty much call any throwing statement.

Afaik, the only valid protection against this to prevent exceptions in the first place.

0
source

Source: https://habr.com/ru/post/1672458/


All Articles