Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a type safe to throw in C++

Tags:

c++

exception

This is a theoretical question to understand better how exceptions work.

What do I need to check in order to make sure my class is safe to throw? What actually happens when I throw an exception from the stack point of view?

For example, if I create an object in the stack, it should be destroyed when I go out of scope, but what happens when I throw that object? Is it safe to do that or do I have to create the object on the heap?

Thanks a lot!

like image 941
TCS Avatar asked Mar 21 '23 15:03

TCS


1 Answers

"The exception object is copied to a special location to survive the stack unwinding."

How are exceptions allocated on the stack caught beyond their scope?

And no, it is not a good practice to create the exception in the heap, because then you will have to manage it in the catch block. The standard is to throw by value and catch by reference. Check these for more information:

C++ catch blocks - catch exception by value or reference?

catch exception by pointer in C++

like image 73
Rafid Avatar answered Apr 21 '23 00:04

Rafid