ZetCode

Julia Exceptions Tutorial

last modified November 18, 2026

An exception is an object that signals that something went wrong. Raising one interrupts the normal flow of the program until the exception is handled. Julia uses exceptions for errors such as calling a function with invalid arguments or accessing an array out of bounds.

This tutorial covers raising exceptions with error and throw, handling them with try, catch, else, and finally, defining custom exception types, and passing an exception on with rethrow. The examples were verified with Julia 1.13.4.

Raising an Exception with error

The error function raises an ErrorException with a message. It is the simplest way to report a failure.

main.jl
try
    error("something went wrong")
catch e
    println("caught: ", e)
    println("type: ", typeof(e))
end

The error call creates the exception and interrupts the try block. The catch clause receives it in the variable e. Printing the object with println shows its constructor form, ErrorException("..."), while typeof confirms the type.

$ julia main.jl
caught: ErrorException("something went wrong")
type: ErrorException

throw and Built-In Exceptions

The throw function raises any exception object. Julia defines several standard exception types for common situations.

main.jl
try
    throw(DomainError(-1, "sqrt needs a non-negative argument"))
catch e
    println(typeof(e))
    println(e)
end

DomainError reports a value outside the valid domain of an operation; it carries the offending value and a message. Other built-in types include ArgumentError, BoundsError, and DivideError. Choosing a specific type lets calling code react to the kind of problem rather than parsing a message.

$ julia main.jl
DomainError
DomainError(-1, "sqrt needs a non-negative argument")

Handling Exceptions with try/catch

A try block runs code that may fail; a catch block runs when an exception is raised inside it.

main.jl
try
    println("before")
    error("boom")
    println("after")
catch e
    println("caught: ", e)
end
println("done")

The first line runs normally. When error raises the exception, the rest of the try block is skipped — "after" is never printed. Control moves to catch, and after the handler finishes, execution continues with the statement following the whole construct.

$ julia main.jl
before
caught: ErrorException("boom")
done

Catching a Specific Exception Type

A handler can inspect the exception and decide whether to handle it or pass it on.

main.jl
function divide(a, b)
    try
        return div(a, b)
    catch e
        if e isa DivideError
            return "cannot divide by zero"
        end
        rethrow()
    end
end
println(divide(10, 2))
println(divide(10, 0))

The div function performs integer division and raises a DivideError for a zero divisor. We use isa to check the type and return a friendly message; any other exception reaches the rethrow() call and continues up the call stack. Note that floating point division, 10 / 0, would produce Inf instead of an exception.

$ julia main.jl
5
cannot divide by zero

The else Clause

An else clause runs only when the try block completes without raising an exception.

main.jl
try
    println("no problem here")
catch e
    println("caught an error")
else
    println("the else branch runs when there is no error")
end

Here nothing goes wrong, so the catch clause is skipped and the else branch runs. Keeping the success path in else separates it from code that could raise the exception being caught.

$ julia main.jl
no problem here
the else branch runs when there is no error

The finally Clause

A finally clause always runs, whether or not an exception occurred. It is meant for cleanup such as closing a file or releasing a resource.

main.jl
function run(flag)
    try
        println("start")
        if flag
            error("failure")
        end
        println("success")
    finally
        println("cleanup always runs")
    end
end
run(false)
try
    run(true)
catch e
    println("caught")
end

The first call finishes normally and still prints the cleanup message. In the second call error interrupts the try block, yet the cleanup runs before the exception is caught by the outer handler. Because it runs on every path, finally must not contain code that can itself fail unexpectedly.

$ julia main.jl
start
success
cleanup always runs
start
cleanup always runs
caught

Custom Exception Types

An application can define its own exception types by making a struct a subtype of Exception.

main.jl
struct ValidationError <: Exception
    field::Symbol
    message::String
end

Base.showerror(io::IO, e::ValidationError) =
    print(io, "validation failed for ", e.field, ": ", e.message)

try
    throw(ValidationError(:age, "must be positive"))
catch e
    showerror(stdout, e)
    println()
end

The struct carries the name of the invalid field and an explanation. Defining Base.showerror controls how the exception is displayed by Julia's error reporting; println uses the ordinary show method instead, so we call showerror directly here to display our message. Custom types let callers catch exactly the failures your code can produce.

$ julia main.jl
validation failed for age: must be positive

rethrow

Sometimes a handler needs to log an exception and let a caller deal with it. The rethrow function passes the current exception on unchanged.

main.jl
try
    try
        error("inner problem")
    catch e
        println("inner handler: ", e)
        rethrow()
    end
catch e
    println("outer handler: ", e)
end

The inner catch prints the exception and then calls rethrow with no argument, which raises the same object again. The outer catch receives it and prints it in turn. Without rethrow, the exception would be swallowed after the inner handler.

$ julia main.jl
inner handler: ErrorException("inner problem")
outer handler: ErrorException("inner problem")

A Practical Example

Exception handling is useful when an operation may legitimately fail, such as parsing text supplied by a user.

main.jl
function parse_age(s::String)
    n = try
        parse(Int, s)
    catch
        return nothing
    end
    return n >= 0 ? n : nothing
end
println(parse_age("42"))
println(parse_age("abc"))
println(parse_age("-5"))

The value of a try expression is the value of its last statement, so the result of parse is assigned to n. If parsing fails, the catch branch returns nothing. A valid number is returned only when it is non-negative; the ternary operator ? : chooses between the two results. The function therefore always returns either an integer or nothing.

$ julia main.jl
42
nothing
nothing

Best Practices for Exceptions

A few guidelines keep error handling clear.

Source

Julia Control Flow documentation

Julia Exception Handling documentation

In this article we have handled Julia exceptions: raising them with error and throw, using try, catch, else, and finally, defining custom exception types, and rethrowing. Control flow in general is covered in Julia control flow, and the Nothing type used in the last example is explained in Julia abstract types. Custom exception types are ordinary structs as described in Julia structs.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Julia tutorials.