Killrazor
Killrazor

Reputation: 7184

How to do my own custom runtime error class?

I'm trying to do a simple custom runtime_error. I define the 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 the 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;
     }

Runtime error is correctly thrown as FileNotFoundException but the line with std::cout is never reached and no line is writed to the console.

All ideas are welcome. Thanks!

Upvotes: 8

Views: 10648

Answers (4)

Vadim Sukhorukov
Vadim Sukhorukov

Reputation: 131

BTW, with the following declaration you create a copy of the msg string.

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

Write "const std::string& msg" instead. It will put just a reference on a stack. While now you put the whole string on a stack.

Upvotes: 1

gregg
gregg

Reputation: 1027

You are actually throwing a pointer to a heap allocated object (FileNotFoundException*) so the types don't match. Generally, throw by value and catch by reference (rule 73).

Upvotes: 3

user180326
user180326

Reputation:

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

Upvotes: 6

GManNickG
GManNickG

Reputation: 504303

That's because you're throwing a pointer. Just do: throw FileNotFoundException(msg);.

Whenever you use a pointer, unless you're putting it into a container/wrapper you're probably not doing the right thing.

Upvotes: 16

Related Questions