:@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
-
Basic assertion:
julia> x = 5; julia> @assert x > 0;The
@assertmacro is used to check if the conditionx > 0is true. If the condition is false, it throws anAssertionErrorwith a default error message. -
Assertion with custom error message:
julia> y = 10; julia> @assert y < 5 "Value of y should be less than 5";Here, the
@assertmacro checks if the conditiony < 5is true. If the condition is false, it throws anAssertionErrorwith the provided error message. -
Assertion within a function:
function divide(a, b) @assert b != 0 "Cannot divide by zero" return a / b endIn this example, the
@assertmacro is used inside a function to check ifbis not equal to zero. If the condition is false, it throws anAssertionErrorwith 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.