56 lines · plain
1.. title:: clang-tidy - bugprone-unhandled-exception-at-new2 3bugprone-unhandled-exception-at-new4===================================5 6Finds calls to ``new`` with missing exception handler for ``std::bad_alloc``.7 8Calls to ``new`` may throw exceptions of type ``std::bad_alloc`` that should9be handled. Alternatively, the nonthrowing form of ``new`` can be10used. The check verifies that the exception is handled in the function11that calls ``new``.12 13If a nonthrowing version is used or the exception is allowed to propagate out14of the function no warning is generated.15 16The exception handler is checked if it catches a ``std::bad_alloc`` or17``std::exception`` exception type, or all exceptions (catch-all).18The check assumes that any user-defined ``operator new`` is either19``noexcept`` or may throw an exception of type ``std::bad_alloc`` (or one20derived from it). Other exception class types are not taken into account.21 22.. code-block:: c++23 24 int *f() noexcept {25 int *p = new int[1000]; // warning: missing exception handler for allocation failure at 'new'26 // ...27 return p;28 }29 30.. code-block:: c++31 32 int *f1() { // not 'noexcept'33 int *p = new int[1000]; // no warning: exception can be handled outside34 // of this function35 // ...36 return p;37 }38 39 int *f2() noexcept {40 try {41 int *p = new int[1000]; // no warning: exception is handled42 // ...43 return p;44 } catch (std::bad_alloc &) {45 // ...46 }47 // ...48 }49 50 int *f3() noexcept {51 int *p = new (std::nothrow) int[1000]; // no warning: "nothrow" is used52 // ...53 return p;54 }55 56