🎓 A1Learner
🔍
0 of 48 lessons completed

Julia Exception Types

Exception types are names for different kinds of errors. Julia gives each error a type so a program can tell errors apart.

Zero division has its own type

Integer division by zero fails. The catch block prints only the error type.

try
    div(1, 0)
catch e
    println(typeof(e))
end

A bad value has its own type

The square root of a negative number is not allowed. The catch block prints only the error type.

try
    sqrt(-4.0)
catch e
    println(typeof(e))
end

A wrong argument type has its own type

This function accepts only integers. Calling it with text fails, and the catch block prints only the error type.

function double_int(x::Int)
    2 * x
end
try
    double_int("hi")
catch e
    println(typeof(e))
end

Example

function double_int(x::Int)
    2 * x
end
try
    div(1, 0)
catch e
    println(typeof(e))
end
try
    sqrt(-4.0)
catch e
    println(typeof(e))
end
try
    double_int("hi")
catch e
    println(typeof(e))
end

Key points

  • DivideError: Dividing an integer by zero raises this error.
  • DomainError: A value outside a function's allowed range raises this error.
  • MethodError: Calling a function with a wrong argument type raises this error.
  • Catch by type: A catch block can handle each error type in its own way.
  • Print the type: Printing typeof(e) shows the error type as a plain name.

In this example, the first block divides by zero, the second takes a square root of a negative number, and the third calls a function with text. Each catch block prints only the type of its error.

Note

Never print the caught error value itself, because its text can vary.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

What does typeof(e) print when div(1, 0) is caught?