throw
throw(e)
Throw an object as an exception
Examples
In the Julia programming language, the function throw(e)
is used to throw an object as an exception.
julia> throw(DomainError("Invalid input"))
ERROR: DomainError with message Invalid input
Stacktrace:
[1] top-level scope
@ REPL[1]:1
Here are some common examples of using throw
:
-
Throw a custom exception:
julia> throw(ArgumentError("Invalid argument")) ERROR: ArgumentError: Invalid argument Stacktrace: [1] top-level scope @ REPL[1]:1
This example throws an
ArgumentError
with the message "Invalid argument". - Throw an exception with additional information:
julia> value = -5; julia> if value < 0 throw(DomainError("Value cannot be negative", value)) end ERROR: DomainError with message Value cannot be negative Value: -5 Stacktrace: [1] top-level scope @ REPL[2]:2
In this example, a
DomainError
is thrown with the message "Value cannot be negative" and the value-5
is attached to the exception for additional information.
Common mistake example:
julia> throw("Invalid input")
ERROR: MethodError: no method matching throw(::String)
Closest candidates are:
throw(::Any, ::Any...) at exceptions.jl:104
Stacktrace:
[1] top-level scope
@ REPL[1]:1
In this example, a string is directly passed to throw
, which results in a MethodError
. The correct usage is to pass an exception object instead of a string as an argument to throw
.
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.