This language bar is your friend. Select your favorite languages!

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.

die "Invalid argument $x";
import std.format;
throw new Exception("invalid value for x (%s) in '%s'".format(x, __PRETTY_FUNCTION__));
void foo(int x)
in
{
    assert(x != 0, "wrong value for x");
}
body
{
    // function
}
error(badarg).
return nil, fmt.Errorf("invalid value for x: %v", x)
sqrt' :: Int -> Either String Int
sqrt' x | x < 0 = Left "Invalid argument"
sqrt' x         = Right (sqrt x)
throw new IllegalArgumentException("Invalid value for x:" + x);
return nil, "Invalid argument x"
throw new InvalidArgumentException($x . " is invalid.");
Uses sysutils, math;
Raise EInvalidArgument.CreatFmt('Invalid value: %d',[x]);
raise ValueError("x is invalid")
raise ArgumentError, "invalid value #{x}."
enum CustomError { InvalidAnswer }

fn do_stuff(x: i32) -> Result<i32, CustomError> {
    if x != 42 {
        Err(CustomError::InvalidAnswer)
    } else {
        Ok(x)
    }
}

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

programming-idioms.org

Related idioms