# Are exceptions in Julia "Zero Cost"

**URL:** <https://discourse.julialang.org/t/are-exceptions-in-julia-zero-cost/38405>\
**Category:** Performance\
**Created:** [April 29, 2020, 2:18am UTC](https://discourse.julialang.org/t/are-exceptions-in-julia-zero-cost/38405 "2020-04-29T02:18:20Z")\
**Posts on this page:** 1\
**Showing post:** 8

<div class="post-metadata">

**Author:** ![StefanKarpinski](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stefankarpinski/32/24_2.png) [@StefanKarpinski](https://discourse.julialang.org/u/StefanKarpinski)\
**Post date:** [April 29, 2020, 2:19pm UTC](https://discourse.julialang.org/t/are-exceptions-in-julia-zero-cost/38405/8 "2020-04-29T14:19:54Z")

</div>

It would be interesting to see what you tried. The test is, of course, not zero-cost: you still have to execute the condition to see if the exception should be triggered. I’m not seeing any difference, although there is some inconsistency in the `@btime` results:

```julia
function f(n::Int)
    x = rand(Int)
    t = 0
    try
        for i = 1:n
            i == x && error("bad i value")
            t += i
        end
    catch
    end
    return t
end

function g(n::Int)
    x = rand(Int)
    t = 0
    for i = 1:n
        i == x && break
        t += i
    end
    return t
end

```

and timings:

```julia
julia> using BenchmarkTools

julia> @btime f(10_000)
  4.541 μs (0 allocations: 0 bytes)
50005000

julia> @btime g(10_000)
  2.296 μs (0 allocations: 0 bytes)
50005000

julia> @btime g(10_000)
  4.517 μs (0 allocations: 0 bytes)
50005000

julia> @btime f(10_000)
  4.540 μs (0 allocations: 0 bytes)
50005000

julia> @btime g(10_000)
  4.516 μs (0 allocations: 0 bytes)
50005000

julia> @btime f(10_000)
  4.540 μs (0 allocations: 0 bytes)
50005000

```

There’s that one `@btime` for `g(10_000)` that’s 2.296 μs but I’ve seen that for `f(10_000)` as well, although far less often. Could be something to do with the branch predictor.

---

_[View the full topic](https://discourse.julialang.org/t/are-exceptions-in-julia-zero-cost/38405)._
