Be concise.
Be useful.
All contributions dictatorially edited by webmasters to match personal tastes.
Please do not paste any copyright violating material.
Please try to avoid dependencies to third-party libraries and frameworks.
- Java
- Java
- Java
- Java
- PHP
- Python
- C
- C++
- C#
- D
- D
- Erlang
- Fortran
- Go
- Groovy
- Haskell
- JS
- Lua
- Lua
- Pascal
- Perl
- Ruby
- Rust
void f(int x) {
Objects.checkIndex(x, 123);
}
<T> void f(T x) throws Exception {
if (x != value) throw new Exception();
}
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.
<T> void f(T x) {
Objects.requireNonNull(x);
}
throw new \InvalidArgumentException($x . ' is invalid.');
Use a backslash if you are inside a namespace that hasn't pulled in InvalidArgumentException.
raise ValueError("x is invalid")
enum {
E_OK,
E_OUT_OF_RANGE
};
int square(int x, int *result) {
if (x > 1073741823) {
return E_OUT_OF_RANGE;
}
*result = x*x;
return E_OK;
}
throw domain_error("oops!");
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.
if (x > largest_value) error stop "Illegal value in function."
This will also stop all other images.
throw new IllegalArgumentException("Invalid value for x: $x")
sqrt' :: Int -> Either String Int
sqrt' x | x < 0 = Left "Invalid argument"
sqrt' x = Right (sqrt x)
throw new Error('x is invalid');
return nil, "Invalid argument x"
error("Invalid argument x")
die "Invalid argument $x";
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.