xref: /llvm-project/clang-tools-extra/docs/clang-tidy/checks/bugprone/unhandled-exception-at-new.rst (revision 6e566bc5523f743bc34a7e26f050f1f2b4d699a8)
1.. title:: clang-tidy - bugprone-unhandled-exception-at-new
2
3bugprone-unhandled-exception-at-new
4===================================
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 should
9be handled. Alternatively, the nonthrowing form of ``new`` can be
10used. The check verifies that the exception is handled in the function
11that calls ``new``.
12
13If a nonthrowing version is used or the exception is allowed to propagate out
14of the function no warning is generated.
15
16The exception handler is checked if it catches a ``std::bad_alloc`` or
17``std::exception`` exception type, or all exceptions (catch-all).
18The check assumes that any user-defined ``operator new`` is either
19``noexcept`` or may throw an exception of type ``std::bad_alloc`` (or one
20derived 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
56