🎓 A1Learner
🔍
0 of 52 lessons completed

Julia Error Handling

Error handling is code that catches a failure and decides what happens next. It lets a program respond in a calm and planned way.

catch runs when parse fails

The text abc cannot become a whole number. The catch block prints the fixed message.

try
    number = parse(Int, "abc")
    println(number)
catch
    println("That was not a whole number.")
end

The program keeps running after catch

The same failure is caught here. A line after the form still prints.

try
    number = parse(Int, "abc")
    println(number)
catch
    println("That was not a whole number.")
end
println("The program keeps running.")

catch is skipped when nothing fails

The text 42 parses with no failure. Only the try result prints.

try
    number = parse(Int, "42")
    println(number + 8)
catch
    println("That was not a whole number.")
end

Example

try
    number = parse(Int, "xyz")
    println(number)
catch
    println("That was not a whole number.")
end
number = parse(Int, "10")
println(number * 3)

Key points

  • try: a block that runs code that might fail.
  • catch: a block that runs only when the try block fails.
  • end: a keyword that closes the whole try and catch form.
  • Fixed message: the catch block here prints a plain message chosen by the programmer.
  • Continue: lines after the whole form still run after a caught failure.

In this example, parsing xyz fails, so the catch block prints the fixed message. The program then continues past the form. A fresh parse of 10 succeeds, and the last line prints 30.

Note

The exception value itself is not printed in these lessons because its text is long and changes with the failure.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

When does the catch block run?