How to execute your own custom class of runtime errors?

I am trying to make a simple custom runtime_error. I define a class:

#include <string> #include <stdexcept> namespace utils{ class FileNotFoundException: public std::runtime_error{ public: FileNotFoundException():runtime_error("File not found"){} FileNotFoundException(std::string msg):runtime_error(msg.c_str()){} }; }; 

Then I throw an error:

 bool checkFileExistence( std::string fileName ) { boost::filesystem::path full_path = boost::filesystem::system_complete(boost::filesystem::path(fileName)); if (!boost::filesystem::exists(full_path)) { char msg[500]; _snprintf(msg,500,"File %s doesn't exist",fileName.c_str()); throw new FileNotFoundException(msg); } } 

And I use a try / catch block

  try{ checkFileExistence(fileName); } catch(utils::FileNotFoundException& fnfe) { std::cout << fnfe.what() << std::endl; } 

A runtime error was correctly selected as a FileNotFoundException, but a line with std :: cout will never be reached, and no line will be sent to the console.

Any ideas are welcome. Thanks!

+6
c ++ exception
source share
4 answers

This is because you are throwing a pointer. Just do: throw FileNotFoundException(msg); .

Whenever you use a pointer, if you do not put it in a container / wrapper, you are probably not doing the right thing.

+13
source share

You write throw new FileNotFoundException(msg) , it should be "throw FileNotFoundException (msg)". The rule is thrown by value, catch by reference.

+5
source share

You are actually casting a pointer to the selected heap object (FileNotFoundException *) so that the types do not match. As a rule, throw by value and catch by reference ( rule 73 ).

+3
source share

BTW, with the following declaration, you are making a copy of the msg line.

 FileNotFoundException(std::string msg):runtime_error(msg.c_str()){} 

Instead, write "const std :: string & msg". It will only put a link to the stack. While you push the entire line onto the stack.

+1
source share

All Articles