:@assert

@assert cond [text]

Throw an AssertionError if cond is false. Preferred syntax for writing assertions. Message text is optionally displayed upon assertion failure.

Examples

  1. Basic assertion:

    julia> x = 5;
    julia> @assert x > 0;

    The @assert macro is used to check if the condition x > 0 is true. If the condition is false, it throws an AssertionError with a default error message.

  2. Assertion with custom error message:

    julia> y = 10;
    julia> @assert y < 5 "Value of y should be less than 5";

    Here, the @assert macro checks if the condition y < 5 is true. If the condition is false, it throws an AssertionError with the provided error message.

  3. Assertion within a function:

    function divide(a, b)
       @assert b != 0 "Cannot divide by zero"
       return a / b
    end

    In this example, the @assert macro is used inside a function to check if b is not equal to zero. If the condition is false, it throws an AssertionError with the specified error message. This helps to ensure that the function is not called with an invalid argument.

Common mistake example:

julia> z = 0;
julia> @assert z != 0
AssertionError: z != 0

In this example, the condition z != 0 is false, which triggers the AssertionError. It's important to carefully evaluate the condition to ensure it matches the intended assertion.

See Also

User Contributed Notes

Add a Note

The format of note supported is markdown, use triple backtick to start and end a code block.

*Required Field
Details

Checking you are not a robot: