Skip to content

Commit bb85080

Browse files
committed
refactored argument not found
1 parent 5332026 commit bb85080

2 files changed

Lines changed: 10 additions & 5 deletions

File tree

argparse.h

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,10 +31,15 @@
3131
#include <vector>
3232

3333
class ArgumentParser {
34+
private:
35+
struct Argument;
36+
3437
public:
35-
class ArgumentException : public std::runtime_error {
38+
class ArgumentNotFound : public std::runtime_error {
3639
public:
37-
ArgumentException(const char *msg) noexcept : std::runtime_error(msg) {}
40+
ArgumentNotFound(ArgumentParser::Argument &arg) noexcept
41+
: std::runtime_error(
42+
("Required argument not found: " + arg._name).c_str()) {}
3843
};
3944

4045
ArgumentParser(const std::string &desc) : _desc(desc), _help(false) {}
@@ -88,8 +93,7 @@ class ArgumentParser {
8893
for (auto &a : _arguments) {
8994
if (a._required) {
9095
if (_variables.find(a._name) == _variables.end()) {
91-
throw ArgumentException(
92-
("Required argument not found: " + a._name).c_str());
96+
throw ArgumentNotFound(a);
9397
}
9498
}
9599
}
@@ -119,6 +123,7 @@ class ArgumentParser {
119123
}
120124

121125
private:
126+
friend class ArgumentNotFound;
122127
struct Argument {
123128
public:
124129
Argument(const std::string &name, const std::string &desc,

example.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ int main(int argc, char* argv[]) {
2828
parser.add_argument("-v", "a vector", true);
2929
try {
3030
parser.parse(argc, argv);
31-
} catch (const ArgumentParser::ArgumentException& ex) {
31+
} catch (const ArgumentParser::ArgumentNotFound& ex) {
3232
std::cout << ex.what() << std::endl;
3333
return 0;
3434
}

0 commit comments

Comments
 (0)