Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What to throw when throwing C++ exceptions?

Tags:

c++

exception

This might be kind of a silly question, but in C++, when I want to throw an exception.. what do I throw?

Am I supposed to throw std::exception, or is that reserved by the standard library? Or should I throw a string or int? Or should I just throw whatever I feel is appropriate?


1 Answers

Throw a class that's derived from std::exception; if you #include <stdexcept>, you can pick from a number of ready-made, useful derived classes.

Deriving from std::exception allows your handlers to follow a recognizable style, as you can always use .what() to get a textual message. Don't throw primitive types, since they carry no semantic information.

like image 185
Kerrek SB Avatar answered Sep 13 '25 10:09

Kerrek SB