In Java if an input argument to a method is invalid, we can throw an IllegalArgumentException
(which is of type RuntimeException
). In C++, there is no notion of checked and unchecked exceptions. Is there a similar exception in standard C++ which can be used to indicate a runtime exception? Or is there a common style not in the standard but everyone follows in practice for a situation like this?
Or, should I just create my own custom exception and throw it?
IllegalArgumentException is a Java exception indicating that a method has received an argument that is invalid or inappropriate for this method's purposes.
This exception is thrown in order to indicate that a method has been passed an illegal or inappropriate argument. For example, if a method requires a non-empty string as a parameter and the input string equals null, the IllegalArgumentException is thrown to indicate that the input parameter cannot be null.
public int calculateFactorial(int n) { if (n < 0) throw new IllegalArgumentException("n must be positive"); if (n >= 60) throw new IllegalArgumentException("n must be < 60"); ... } If you know that a parameter to your method cannot be null, then it is best to explicitly check for null and throw a NullPointerException.
If we want to catch the IllegalArgumentException then we can use try-catch blocks. By doing like this we can handle some situations. Suppose in catch block if we put code to give another chance to the user to input again instead of stopping the execution especially in case of looping.
Unlike Java, C++ does not have a "standard framework" but only a small (and optional) standard library. Moreover, there are different opinions under C++ programmers whether to use exceptions at all.
Therefore you will find different recommendations by different people: Some like to use exception types from the standard library, some libraries (e.g. Poco) use a custom exception hierarchy (derived from std::exception), and others don't use exceptions at all (e.g. Qt).
If you want to stick to the standard library, there exists a specialized exception type: invalid_argument
(extends logic_error
).
#include <stdexcept> // ... throw std::invalid_argument("...");
For the reference: Here is an overview of standard exception types defined (and documented) in stdexcept
:
exception logic_error domain_error invalid_argument length_error out_of_range runtime_error range_error overflow_error underflow_error
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With