Throw an object as an exception


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
 [1] top-level scope
   @ REPL[1]:1

Here are some common examples of using throw:

  1. Throw a custom exception:

    julia> throw(ArgumentError("Invalid argument"))
    ERROR: ArgumentError: Invalid argument
    [1] top-level scope
      @ REPL[1]:1

    This example throws an ArgumentError with the message "Invalid argument".

  2. Throw an exception with additional information:
    julia> value = -5;
    julia> if value < 0
              throw(DomainError("Value cannot be negative", value))
    ERROR: DomainError with message Value cannot be negative
    [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
 [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.

*Required Field

Checking you are not a robot: