:@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
@assert
macro is used to check if the conditionx > 0
is true. If the condition is false, it throws anAssertionError
with 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
@assert
macro checks if the conditiony < 5
is true. If the condition is false, it throws anAssertionError
with the provided error message. -
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 ifb
is not equal to zero. If the condition is false, it throws anAssertionError
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.