199k views
4 votes
How to throw invalid argument exception in C++?

1 Answer

7 votes

Final answer:

In C++, to throw an invalid_argument exception, include the header file and use the 'throw' keyword followed by the std::invalid_argument with an error message when a function argument's value is inappropriate.

Step-by-step explanation:

To throw an invalid_argument exception in C++, you need to include the <stdexcept> header file that defines the standard exception classes that both the library and programs can use to report common errors. You can throw an invalid_argument exception when a function receives an argument that has the right type but an inappropriate value.

Example:

#include <iostream>
#include <stdexcept>

void exampleFunction(int value) {
if (value < 0) {
throw std::invalid_argument("Received negative value");
}
// Rest of the function
}

int main() {
try {
exampleFunction(-1);
} catch (const std::invalid_argument& e) {
std::cerr << "Caught an invalid_argument exception: " << e.what() << std::endl;
}
return 0;
}

In this code snippet, the function exampleFunction checks whether the value passed to it is negative. If it is, the function throws an invalid_argument exception that can be caught and handled by the try-catch block in the main function.

User Lurch
by
8.0k points