Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do my own custom runtime error class?

Tags:

c++

exception

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!

like image 988
Killrazor Avatar asked Sep 10 '10 21:09

Killrazor


People also ask

What are some example runtime errors?

Here are some examples of common runtime errors you are sure to encounter: Misspelled or incorrectly capitalized variable and function names. Attempts to perform operations (such as math operations) on data of the wrong type (ex. attempting to subtract two variables that hold string values)

Why does my code say runtime error?

These errors occur when: Invalid mathematical operations are executed. For example, when you try to divide a number by zero, calculate the square root of a negative number etc.

What is runtime error in laptop?

In this article For more information, see aka.ms/iemodefaq. A runtime error is a software or hardware problem that prevents Internet Explorer from working correctly. Runtime errors can be caused when a website uses HTML code that's incompatible with the web browser functionality.


1 Answers

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.

like image 129
GManNickG Avatar answered Nov 12 '22 02:11

GManNickG