# Is there a better way to do error handling on Julia than try/catch?

**URL:** <https://discourse.julialang.org/t/is-there-a-better-way-to-do-error-handling-on-julia-than-try-catch/21716>\
**Category:** General Usage\
**Created:** [March 10, 2019, 8:43pm UTC](https://discourse.julialang.org/t/is-there-a-better-way-to-do-error-handling-on-julia-than-try-catch/21716 "2019-03-10T20:43:59Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![mrkaspa](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mrkaspa/32/7236_2.png) [@mrkaspa](https://discourse.julialang.org/u/mrkaspa)\
**Post date:** [March 10, 2019, 8:43pm UTC](https://discourse.julialang.org/t/is-there-a-better-way-to-do-error-handling-on-julia-than-try-catch/21716/1 "2019-03-10T20:43:59Z")

</div>

Julia could make error types by using Union or maybe a la Golang with tuples, why does it choose to use the terrible approach that is to treat errors as exceptions?. To differentiate this brings better logic flow to the code as the case for Elixir or Golang that handle errors and exceptions pretty different

---

<div class="post-metadata">

**Author:** ![rdeits](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rdeits/32/286_2.png) [@rdeits](https://discourse.julialang.org/u/rdeits)\
**Post date:** [March 10, 2019, 9:00pm UTC](https://discourse.julialang.org/t/is-there-a-better-way-to-do-error-handling-on-julia-than-try-catch/21716/2 "2019-03-10T21:00:37Z")

</div>

You can certainly choose any of those patterns in your own code, since Julia already supports multiple return values (or, really, returning and unpacking tuples) and various kinds of option types like `Some{T}` and `Union{T, Nothing}`.

> [@mrkaspa](#):
>
> why does it choose to use the terrible approach that is to treat errors as exceptions?

This kind of tone is not likely to lead to a productive or helpful discussion in a forum like this. Julia is the product of a lot of design choices, none of which are perfect, but calling something a “terrible approach” is more likely to lead to pointless bickering than to an actual discussion about how to improve the language.

---

<div class="post-metadata">

**Author:** ![tamasgal](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamasgal/32/27946_2.png) [@tamasgal](https://discourse.julialang.org/u/tamasgal)\
**Post date:** [March 10, 2019, 10:05pm UTC](https://discourse.julialang.org/t/is-there-a-better-way-to-do-error-handling-on-julia-than-try-catch/21716/3 "2019-03-10T22:05:38Z")

</div>

I think Julia and especially its type system combined with multiple dispatch are really powerful features which allow you to implement whatever error handling design you like.  
This starts with basic try/catch, over things like Robin mentioned (optionals/unions) and goes as far as implementing your own monads like you do in e.g. Haskell (with the tiny difference that in Julia you don’t really have to worry about speed 😉 ).

---

<div class="post-metadata">

**Author:** ![oxinabox](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/oxinabox/32/206603_2.png) [@oxinabox](https://discourse.julialang.org/u/oxinabox)\
**Post date:** [March 11, 2019, 12:35am UTC](https://discourse.julialang.org/t/is-there-a-better-way-to-do-error-handling-on-julia-than-try-catch/21716/4 "2019-03-11T00:35:27Z")

</div>

You might be interested in [ResultTypes.jl](https://github.com/iamed2/ResultTypes.jl).

---

<div class="post-metadata">

**Author:** ![mrkaspa](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mrkaspa/32/7236_2.png) [@mrkaspa](https://discourse.julialang.org/u/mrkaspa)\
**Post date:** [March 11, 2019, 3:33am UTC](https://discourse.julialang.org/t/is-there-a-better-way-to-do-error-handling-on-julia-than-try-catch/21716/5 "2019-03-11T03:33:07Z")

</div>

I did not mean to offend but it is not the best error handling

---

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [March 11, 2019, 6:26am UTC](https://discourse.julialang.org/t/is-there-a-better-way-to-do-error-handling-on-julia-than-try-catch/21716/6 "2019-03-11T06:26:52Z")

</div>

It is _one_ approach to error handling, which is useful in some situations, less so in others. As @rdeits said, Julia is flexible enough to allow you to experiment with other approaches. Many functions in `Base` and in packages have a form that uses a type union instead of throwing an error, eg `Base.tryparse`, you can of course follow this pattern with your own functions.

---

<div class="post-metadata">

**Author:** ![DNF](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dnf/32/10191_2.png) [@DNF](https://discourse.julialang.org/u/DNF)\
**Post date:** [March 11, 2019, 8:23am UTC](https://discourse.julialang.org/t/is-there-a-better-way-to-do-error-handling-on-julia-than-try-catch/21716/7 "2019-03-11T08:23:32Z")

</div>

What’s wrong with `try/catch`? Serious question.

---

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [March 11, 2019, 8:57am UTC](https://discourse.julialang.org/t/is-there-a-better-way-to-do-error-handling-on-julia-than-try-catch/21716/8 "2019-03-11T08:57:39Z")

</div>

> [@DNF](#):
>
> What’s wrong with `try/catch` ? Serious question.

The problem is mostly practical:

1. it can be costly, even if the exception is not thrown,
2. some tools cannot handle it (eg [Zygote.jl#88](https://github.com/FluxML/Zygote.jl/issues/88))

That said, I would not say that there is anything _wrong_ with `try ...catch` _per se_. It is just a tool from a palette of tools, and if someone wants to use exceptions for control flow, they should just use another tool.

---

<div class="post-metadata">

**Author:** ![kristoffer.carlsson](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/kristoffer.carlsson/32/22_2.png) [@kristoffer.carlsson](https://discourse.julialang.org/u/kristoffer.carlsson)\
**Post date:** [March 11, 2019, 9:36am UTC](https://discourse.julialang.org/t/is-there-a-better-way-to-do-error-handling-on-julia-than-try-catch/21716/9 "2019-03-11T09:36:46Z")

</div>

After looking at [CppCon 2018: Andrei Alexandrescu “Expect the expected” - YouTube](https://www.youtube.com/watch?v=PH4WBuE1BHI&t=2383s) (and before learning about ResultTypes.jl) I made my own version of errors as return values [https://github.com/KristofferC/Expect.jl](https://github.com/KristofferC/Expect.jl).

---

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [March 11, 2019, 9:57am UTC](https://discourse.julialang.org/t/is-there-a-better-way-to-do-error-handling-on-julia-than-try-catch/21716/10 "2019-03-11T09:57:18Z")

</div>

Did you actually end up using it in practice?

---

<div class="post-metadata">

**Author:** ![kristoffer.carlsson](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/kristoffer.carlsson/32/22_2.png) [@kristoffer.carlsson](https://discourse.julialang.org/u/kristoffer.carlsson)\
**Post date:** [March 11, 2019, 10:19am UTC](https://discourse.julialang.org/t/is-there-a-better-way-to-do-error-handling-on-julia-than-try-catch/21716/11 "2019-03-11T10:19:59Z")

</div>

Nope, I didn’t feel it solved any problem I had.

---

<div class="post-metadata">

**Author:** ![piever](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/piever/32/1815_2.png) [@piever](https://discourse.julialang.org/u/piever)\
**Post date:** [March 11, 2019, 10:57am UTC](https://discourse.julialang.org/t/is-there-a-better-way-to-do-error-handling-on-julia-than-try-catch/21716/12 "2019-03-11T10:57:36Z")

</div>

In practice it feels like the choice in Base is to return `nothing` when there is no sensible answer, for example `tryparse` returns `nothing` if things can’t be parsed, or `findfirst` `findlast` return `nothing` if no value is found.

Base aslo provides some tools to work with `nothing` as a return value, i.e. `something(x, val)` (to use default `val` value if `x` is `nothing`), or `isnothing(x) ? do_one_thing : do_another_thing`. I think more syntactic sugar for this is planned: things like `a ?? b` for `something(a, b)`, see [https://github.com/JuliaLang/julia/issues/26303](https://github.com/JuliaLang/julia/issues/26303), or `T?` for `Union{T, Nothing}`.

---

<div class="post-metadata">

**Author:** ![foobar\_lv2](https://avatars.discourse-cdn.com/v4/letter/f/ee59a6/32.png) [@foobar\_lv2](https://discourse.julialang.org/u/foobar_lv2)\
**Post date:** [March 11, 2019, 12:35pm UTC](https://discourse.julialang.org/t/is-there-a-better-way-to-do-error-handling-on-julia-than-try-catch/21716/13 "2019-03-11T12:35:17Z")

</div>

Exceptions are just a control flow primitive for “unwind the call stack” and have inherently nothing to do with error handling. This control flow primitive is occasionally very useful (but remember that it is often slow).

Whether to use this control flow primitive at all, and for what purpose, is up to you.

Most of julia only throws exceptions for things that should be considered programmer error.

---

<div class="post-metadata">

**Author:** ![dhazeghi](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dhazeghi/32/7107_2.png) [@dhazeghi](https://discourse.julialang.org/u/dhazeghi)\
**Post date:** [March 11, 2019, 4:26pm UTC](https://discourse.julialang.org/t/is-there-a-better-way-to-do-error-handling-on-julia-than-try-catch/21716/14 "2019-03-11T16:26:10Z")

</div>

To this point, do you have a sense for how expensive exceptions handling (when not thrown) are in practice? We do use them for things handling parsing errors thrown by the Base code, but we could write our own parsers if that is likely to be much faster. Thanks,

---

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [March 11, 2019, 4:34pm UTC](https://discourse.julialang.org/t/is-there-a-better-way-to-do-error-handling-on-julia-than-try-catch/21716/15 "2019-03-11T16:34:39Z")

</div>

You should benchmark your code, bit in general it is somewhat costly, _even if you don’t throw the exception_. Eg

```julia
using BenchmarkTools

function tryparse2(T, str)
    try
        parse(T, str)
    catch
        nothing
    end
end

xs = randn(1000);
all_valid = string.(xs)
some_invalid = copy(all_valid)
some_invalid[1:10:end] .= "XXX"

```

benchmarks as

```julia
julia> @btime tryparse.($Ref(Float64), $all_valid);
  261.352 μs (1495 allocations: 31.33 KiB)

julia> @btime tryparse2.($Ref(Float64), $all_valid);
  436.388 μs (1495 allocations: 31.33 KiB)

julia> @btime tryparse.($Ref(Float64), $some_invalid);
  341.909 μs (1398 allocations: 30.88 KiB)

julia> @btime tryparse2.($Ref(Float64), $some_invalid);
  5.505 ms (2898 allocations: 102.75 KiB)

```

---

<div class="post-metadata">

**Author:** ![jlperla](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jlperla/32/34332_2.png) [@jlperla](https://discourse.julialang.org/u/jlperla)\
**Post date:** [March 11, 2019, 4:39pm UTC](https://discourse.julialang.org/t/is-there-a-better-way-to-do-error-handling-on-julia-than-try-catch/21716/16 "2019-03-11T16:39:03Z")

</div>

The other general question I have about try/catch and exceptions is whether using things like

```julia
function f(x, a)
    @assert a > 0
    return sqrt(a) * x
end

```

etc. for testing preconditions in the code (e.g. a parameter must be `a > 0`) where I wouldn’t specifically do not want recover and “handle” the errror. Does this introduce all of the same possible possible performance issues and incompatibility with Zygote?

BTW, I sure hope that there is a way to turn off `@assert` at some point as a global setting when launching Julia, or an alternative way to state a bunch of preconditions you only want to check while doing development.

---

<div class="post-metadata">

**Author:** ![foobar\_lv2](https://avatars.discourse-cdn.com/v4/letter/f/ee59a6/32.png) [@foobar\_lv2](https://discourse.julialang.org/u/foobar_lv2)\
**Post date:** [March 11, 2019, 6:11pm UTC](https://discourse.julialang.org/t/is-there-a-better-way-to-do-error-handling-on-julia-than-try-catch/21716/17 "2019-03-11T18:11:56Z")

</div>

> [@dhazeghi](#):
>
> To this point, do you have a sense for how expensive exceptions handling (when not thrown) are in practice?

Exceptions that are not thrown are very cheap (the branches leading to them only prevent certain compiler optimizations).

Setting up an exception handler (the try/catch block) has a certain overhead, and actually throwing them is expensive.

For things like parsing, you should have an outer entry-function that sets up exception handlers, and then calls your internal, likely recursive, parsing functions. That way, you only pay once for the exception handler. This is exactly what exceptions are good for: You need to return to the entry-point of your entire parser, from a dynamic depth of the callstack. Setting up new nested try/catch blocks (i.e. a deep stack of exception handlers) is both slow and defies the point of using exceptions instead of signaling failures via return values.

---

<div class="post-metadata">

**Author:** ![tk3369](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tk3369/32/2824_2.png) [@tk3369](https://discourse.julialang.org/u/tk3369)\
**Post date:** [March 15, 2019, 3:51am UTC](https://discourse.julialang.org/t/is-there-a-better-way-to-do-error-handling-on-julia-than-try-catch/21716/18 "2019-03-15T03:51:09Z")

</div>

> [@foobar\_lv2](#):
>
> This control flow primitive is occasionally very useful (but remember that it is often slow).

Is it slow due to the current implementation? Could it be optimized somehow?

I question about this general statement only because Java apps often deals with layers and layers of exception handling and it’s not slow.

---

<div class="post-metadata">

**Author:** ![bennedich](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/bennedich/32/4894_2.png) [@bennedich](https://discourse.julialang.org/u/bennedich)\
**Post date:** [March 15, 2019, 5:28am UTC](https://discourse.julialang.org/t/is-there-a-better-way-to-do-error-handling-on-julia-than-try-catch/21716/19 "2019-03-15T05:28:13Z")

</div>

Slow is a relative term. What do you refer to by “it’s not slow”? I think of _creating_ exceptions in Java as very slow, and for me that means several microseconds. The costly part is unwinding the call stack and filling in the stack trace. (And in Java production code I’ve seen, the stack depth can be huge.)

I haven’t benchmarked creation and throwing of exceptions in Java vs Julia. To me that doesn’t feel very relevant. You don’t rely on exceptions in performance critical code. Period.

I think that most recommendations about exceptions in Java also apply to Julia: Use exceptions for exceptional conditions, not for regular control flow. Don’t ignore exceptions. Include values of parameters in the exception message. Etc.

---

<div class="post-metadata">

**Author:** ![tk3369](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tk3369/32/2824_2.png) [@tk3369](https://discourse.julialang.org/u/tk3369)\
**Post date:** [March 15, 2019, 3:17pm UTC](https://discourse.julialang.org/t/is-there-a-better-way-to-do-error-handling-on-julia-than-try-catch/21716/20 "2019-03-15T15:17:24Z")

</div>

You’re right. My comment about Java exception handling not being slow is indeed somewhat misguided. Apparently, nothing’s is free when it comes to catching and collecting the stack trace as discussed [here](https://stackoverflow.com/questions/299068/how-slow-are-java-exceptions), [here](https://stackoverflow.com/questions/36343209/which-part-of-throwing-an-exception-is-expensive), and [here](https://stackoverflow.com/questions/8255878/try-catch-performance-java)
