Custom Errors in Julia

# It's possible to use custom types as errors by
# implementing the `showerror` method on them. Here's a
# variant on the example above that uses a custom type
# to explicitly represent an argument error.

# A custom error type usually has the suffix "Error".
struct ArgError <: Exception
    arg::Int
    message::String
end

# Adding this `showerror` method makes `ArgError` implement
# the `Exception` interface.
Base.showerror(io::IO, e::ArgError) = print(io, "$(e.arg) - $(e.message)")

function f(arg::Int)
    if arg == 42
        # Return our custom error.
        throw(ArgError(arg, "can't work with it"))
    end
    return arg + 3
end

function main()
    # `isa` is used to check if an error is of a specific type.
    # If it matches, we can then access its fields.
    try
        f(42)
    catch err
        if err isa ArgError
            println(err.arg)
            println(err.message)
        else
            println("err doesn't match ArgError")
        end
    end
end

main()

This Julia code demonstrates how to create and use custom error types. Here’s a breakdown of the key elements:

  1. We define a custom error type ArgError that inherits from Exception.

  2. We implement the Base.showerror method for our custom error type. This is similar to implementing the Error() method in Go.

  3. The f function demonstrates how to throw our custom error.

  4. In the main function, we use a try-catch block to handle the error. We use isa to check if the caught error is of type ArgError.

  5. If it is an ArgError, we can access its fields (arg and message).

When you run this program, you should see output similar to:

42
can't work with it

This example shows how Julia’s error handling system can be extended with custom types, allowing for more expressive and specific error reporting in your code.