class MyClass {
std::string filename;
public:
MyClass(std::string new_filename);
~MyClass();
}
MyClass.hpp
#include <MyClass.hpp>
MyClass::MyClass(std::string new_filename) {
filename = new_filename;
}
MyClass::~MyClass() {};
MyClass.cpp
I want the constructor only to run when the filename is of a correct form. E.g.: "Name.aa.js".
I tried it with exception handling but I don't quite understand how to use it correctly. I have a function that checks whether the given string parameter is of the correct form.
static bool MyClass::is_filename(std::string name) {
if (regex_match(name, std::regex("(Name.)[a-z]{2}(.js)"))) {
return true;
}
return false;
}
And then I put
if (!is_filename(new_filename)) {
throw;
}
at the beginning of my constructor. When I run my Code with a wrong filename it just outputs "Debug Error", but works with a correct filename. I also tried
throw std::invalid_argument;
But it says
base of all invalid-argument exceptions
no instance of constructor 'std::invalid_argument::invalid_argument' matches the argument list
Where and how exactly do I have to use the throw argument? Do I need to implement try / catch aswell for this to work?
CodePudding user response:
std::invalid_argument
has no default constructor (one that can be called without parameters). There are two constructors taking a message (either as const char*
or std::string
):
throw std::invalid_argument("wrong filename");
Where and how exactly do I have to use the throw argument?
When an object cannot be constructed then the constructor is the right place to throw an exception.
Do I need to implement try / catch aswell for this to work?
Depends. You need no try
/catch
to throw an exception, but if the exception is not caught then your program will terminate.
CodePudding user response:
throw std::invalid_argument("Invalid argument.");
would work. The constructor requires an argument to be passed.
You'll need to catch the exception though somewhere further up the call stack. Do that with
try {
// your function here
} catch (const std::exception& e){
// deal with the exception here, use e.what() to extract the message
}
Alternatively, you can catch std::invalid_argument
or std::logic_error
depending on how generic you want to be.
Note that throw;
on its own can be used at a catch site to throw the current exception by reference. It is the only nullary operator in C .