Fork me on GitHub

Project Notes

C++ Exception Handling

Exercising C++ exception handling.

:arrow_forward: return to the Catalog


The essentials of exception handling in c++:

  • when compiling c++, exception handling is usually turned on by default. But this can be compiler-specific and require switches to enable
  • mulitple catch blocks allow catching different types of errors
  • noexcept specifier indicates the method cannot throw an exception. Bad practice generally.
    • noexcept is an improved version of throw(), which is deprecated in C++11
  • polymorphism applies: must catch exception subclasses before ancestors


exception_handling.cpp runs through a variety of exception classes that are caught:

  • simple ints
  • simple char messages
  • string messages
  • custom exception classes
  • polymorphic standard exceptions

..and ends on an uncaught exception.

NB: this is updated for C++17 syntax - specifically the use of noexcept instead of throw().

$ g++ -std=c++17 -o exception_handling.exe exception_handling.cpp && ./exception_handling.exe

Testing a range of standard and custom exceptions..

Error code: 33
Basic error message: Oh deary me
String error message caught by reference: Out of bacon
bad_alloc error message caught by reference: std::bad_alloc
Generic exception error message caught by reference: std::exception
CustomException message caught by reference: Something bad happened

Now testing an exception in a constructor..

exception_handling.exe(28207,0x7fffae28f380) malloc: *** mach_vm_map(size=1000000000000000) failed (error code=3)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
bad_alloc message: std::bad_alloc

And we're still running!

But the next has no handler:

libc++abi.dylib: terminating with uncaught exception of type int
Abort trap: 6

Credits and References

About LCK#30 C++
Project Source on GitHub Return to the Project Catalog

This page is a web-friendly rendering of my project notes shared in the LittleCodingKata GitHub repository.

LittleCodingKata is my collection of programming exercises, research and code toys broadly spanning things that relate to programming and software development (languages, frameworks and tools).

These range from the trivial to the complex and serious. Many are inspired by existing work and I'll note credits and references where applicable. The focus is quite scattered, as I variously work on things new and important in the moment, or go back to revisit things from the past.

This is primarily a personal collection for my own edification and learning, but anyone who stumbles by is welcome to borrow, steal or reference the work here. And if you spot errors or issues I'd really appreciate some feedback - create an issue, send me an email or even send a pull-request.