0

I would like to write a custom Error class in C++. I am mostly used to Java (not used them a lot) so I would like to check here if my thought process on how to do this in C++ is correct.

Currently I got the following code:

class InvalidInput : public std::runtime_error { public: InvalidInput(const char* msg) : std::runtime_error(msg) { } }; 

I plan on using the cutsom error in a function as so:

myFunc(int x) { if (valueIsInvalid(x)) { throw InvalidInput ("invalid input"); } } 

Before implementing it I would like to know if I am on the right track on how this should be done in C++ (as well as best practice). If there is a better way feel free to tell me as well.

7
  • 1
    Unlike Java, exceptions should be used sparingly in C++. Throwing an exception in C++ is expensive, and should be used only for truly exceptional cases. For input validation en exception should typically only be thrown if the program can't really continue anymore. Commented Dec 2, 2019 at 7:48
  • 2
    Regarding the comment by @Evg, you could also use struct instead of class, as then members will be public by default. Commented Dec 2, 2019 at 7:49
  • 4
    @Someprogrammerdude I would consider human input as so slow (compared to speed of computations) that I wouldn't be afraid about performance impact too much (in this case). Commented Dec 2, 2019 at 7:50
  • 2
    Note that C++ has std::invalid_argument exception. Commented Dec 2, 2019 at 7:52
  • 1
    @DanielsaysreinstateMonica that error class looks like it is meant for input which causes problems with logic. Wrong input in this case will not result in a logic error but will not abide to business rules. Commented Dec 2, 2019 at 7:55

1 Answer 1

1

For your solution as below.

create custome exception

class InvalidInput : public std::exception{ public: InvalidInput(std::string msg):errorMsg_(msg){} virtual const char* what() const throw() { return errorMsg_; } private: std::string errorMsg_; }; 

use of that custome excetion

myFunc(int x) { if (valueIsInvalid(x)) { throw InvalidInput ("invlaid input"); } } 
Sign up to request clarification or add additional context in comments.

1 Comment

You can complete your answer by mentioning that it is possible to const char* what() override

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.