This language bar is your friend. Select your favorite languages!
Select your favorite languages :
- Or search :
Idiom #89 Handle invalid argument
You've detected that the integer value of argument x passed to the current function is invalid. Write the idiomatic way to abort the function execution and signal the problem.
- C
- C++
- C#
- D
- D
- Erlang
- Fortran
- Go
- Groovy
- Haskell
- JS
- Java
- Java
- Java
- Java
- Lua
- Lua
- PHP
- Pascal
- Perl
- Python
- Ruby
- Rust
throw new ArgumentException(nameof(×));
Use the more specific ArgumentOutOfRangeException or ArgumentNullException types if applicable.
void foo(int x)
in
{
assert(x != 0, "wrong value for x");
}
body
{
// function
}
When the software is tested, an input contract can be used to verify x value. In release mode, the input contracts are not included anymore.
throw new IllegalArgumentException("Invalid value for x:" + x);
IllegalArgumentException is a RuntimeException, thus it needn't be declared in the function signature.
Other standard exceptions cover possible cases: NullPointerException, etc.
It is the caller's responsibility to provide valid input, or catch the possible exceptions.
Other standard exceptions cover possible cases: NullPointerException, etc.
It is the caller's responsibility to provide valid input, or catch the possible exceptions.
throw new \InvalidArgumentException($x . ' is invalid.');
Use a backslash if you are inside a namespace that hasn't pulled in InvalidArgumentException.
raise ArgumentError, "invalid value #{x}."
The error-message will automatically be enriched with filename, methodname and linenumber.
enum CustomError { InvalidAnswer }
fn do_stuff(x: i32) -> Result<i32, CustomError> {
if x != 42 {
Err(CustomError::InvalidAnswer)
} else {
Ok(x)
}
}
A function that can have invalid inputs should not panic, but return a Result. The calling function can then determine whether to handle the Err value or unwrap the Result and turn every Err into a panic.