| 1 |
.. title:: clang-tidy - bugprone-unhandled-exception-at-new |
| 2 |
|
| 3 |
bugprone-unhandled-exception-at-new |
| 4 |
=================================== |
| 5 |
|
| 6 |
Finds calls to ``new`` with missing exception handler for ``std::bad_alloc``. |
| 7 |
|
| 8 |
Calls to ``new`` may throw exceptions of type ``std::bad_alloc`` that should |
| 9 |
be handled. Alternatively, the nonthrowing form of ``new`` can be |
| 10 |
used. The check verifies that the exception is handled in the function |
| 11 |
that calls ``new``. |
| 12 |
|
| 13 |
If a nonthrowing version is used or the exception is allowed to propagate out |
| 14 |
of the function no warning is generated. |
| 15 |
|
| 16 |
The exception handler is checked if it catches a ``std::bad_alloc`` or |
| 17 |
``std::exception`` exception type, or all exceptions (catch-all). |
| 18 |
The check assumes that any user-defined ``operator new`` is either |
| 19 |
``noexcept`` or may throw an exception of type ``std::bad_alloc`` (or one |
| 20 |
derived 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 outside |
| 34 |
// of this function |
| 35 |
// ... |
| 36 |
return p; |
| 37 |
} |
| 38 |
|
| 39 |
int *f2() noexcept { |
| 40 |
try { |
| 41 |
int *p = new int[1000]; // no warning: exception is handled |
| 42 |
// ... |
| 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 used |
| 52 |
// ... |
| 53 |
return p; |
| 54 |
} |
| 55 |
|