Post

Exception Cost

Exception Cost

Exception Cost in C++: try-catch vs malloc


Prerequisites


1. Why Exception Matters

C++ exceptions (try-catch) provide safe error handling, but they come with performance considerations.

Especially in performance-critical code, exception usage must be carefully evaluated.

Exceptions are zero-cost when not thrown, but very expensive when thrown

✔ When NOT thrown
1
2
3
4
5
6
7
try 
{
    foo();
} 
catch (...) 
{
}

Almost no runtime cost (modern compilers)

❌ When thrown
1
throw std::bad_alloc();
Heavy operations:
  • Stack unwinding
  • Destructor calls
  • RTTI lookup
  • Control transfer

❌ Can be orders of magnitude slower

2. Instead of Exception, Another

2-1. new vs malloc

new
1
int* p = new int;
  • Calls constructor
  • Throws std::bad_alloc on failure
malloc
1
int* p = (int*)malloc(sizeof(int));
  • No constructor
  • Returns nullptr on failure
  • No exception
Featurenewmalloc
Failure handlingExceptionnullptr
Constructor callYesNo
OverheadHigherLower
SafetyHigherLower

2-1. When to Use malloc

✔ Plain data (POD / primitive types)
✔ Performance-critical paths
✔ When exception handling is undesirable

1
2
3
4
5
int* p = (int*)malloc(sizeof(int));
if (!p) 
{
    // handle error manually
}

2-2. When to Use new

✔ Complex objects
✔ RAII / constructor required
✔ Safety more important than raw speed

2-3. Exception-Free Design

👉 In high-performance systems:

  • Avoid exceptions in hot paths
  • Use error codes or flags
  • Use pre-allocation / object pools
✔ DO
  • Use malloc for simple data in critical loops
  • Check nullptr manually
  • Avoid exception-heavy flows
❌ DON’T
  • Rely on exceptions for normal control flow
  • Use malloc for complex objects
  • Ignore memory initialization

2-4. Advanced Tip

new (std::nothrow)
1
2
3
4
5
int* p = new (std::nothrow) int;
if (!p) 
{
    // handle error
}
  • Avoids exception
  • Returns nullptr like malloc
This post is licensed under CC BY 4.0 by the author.