# Computation termination

**URL:** <https://discourse.julialang.org/t/computation-termination/98046>\
**Category:** General Usage\
**Tags:** question\
**Created:** [April 28, 2023, 3:30pm UTC](https://discourse.julialang.org/t/computation-termination/98046 "2023-04-28T15:30:24Z")\
**Posts on this page:** 19\
**Page:** 1

<div class="post-metadata">

**Author:** ![mst](https://avatars.discourse-cdn.com/v4/letter/m/e0b2c6/32.png) [@mst](https://discourse.julialang.org/u/mst)\
**Post date:** [April 28, 2023, 3:30pm UTC](https://discourse.julialang.org/t/computation-termination/98046/1 "2023-04-28T15:30:24Z")

</div>

Hello,

Say I run `f(g(x))` where `f` has no method for a `Nothing` data type and where `g` is defined as:

```julia
function g(x)
    if condition on x is true
        return a computed valid type for f
    end
end

```

`f`, therefore, will throw a method error if the condition isn’t met; is there a way to terminate the computation of `g` before returning `nothing` to the caller? something like this

```julia
function g(x)
    if condition on x is true
        return a computed valid type for f
    end
    terminate() # without returning `nothing`
end

```

---

<div class="post-metadata">

**Author:** ![hendri54](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/hendri54/32/9621_2.png) [@hendri54](https://discourse.julialang.org/u/hendri54)\
**Post date:** [April 28, 2023, 3:36pm UTC](https://discourse.julialang.org/t/computation-termination/98046/2 "2023-04-28T15:36:30Z")

</div>

It sounds like you are looking for `exit()`.

---

<div class="post-metadata">

**Author:** ![mst](https://avatars.discourse-cdn.com/v4/letter/m/e0b2c6/32.png) [@mst](https://discourse.julialang.org/u/mst)\
**Post date:** [April 28, 2023, 3:46pm UTC](https://discourse.julialang.org/t/computation-termination/98046/3 "2023-04-28T15:46:17Z")

</div>

I tried it, but terminates Julia.

---

<div class="post-metadata">

**Author:** ![sijo](https://avatars.discourse-cdn.com/v4/letter/s/da6949/32.png) [@sijo](https://discourse.julialang.org/u/sijo)\
**Post date:** [April 28, 2023, 3:58pm UTC](https://discourse.julialang.org/t/computation-termination/98046/4 "2023-04-28T15:58:29Z")

</div>

As far as I know there are only two possibilities for the behavior of function `g` (outside of pathological behavior like exiting Julia or making it hang):

1. Function `g` returns a value
2. Function `g` throws an exception

(Any other behavior doesn’t make sense: if you write `y = g(x)` and you “terminate `g` before returning”, what should be the value of `y`?)

Both options can be good choices… If “condition on `x` is false” happens when `g` is called with an invalid value, it makes sense to use an exception (although exceptions are more expensive in terms of performance so sometimes you want to avoid them):

```julia
function g(x)
    if condition on x is true
        return a computed valid type for f
    end
    error("Bad value x: ...")
end

function f(x)
    try
        y = g(x)
    catch
        # Do something in bad case
    end
end

```

Often it is better to let `g` return `Union{Nothing, Float64}` or similar:

```julia
function g(x)
    if condition on x is true
        return a computed valid type for f
    end
end

function f(x)
    y = g(x)
    if isnothing(y)
        ...
    else
        ...
    end
end

```

---

<div class="post-metadata">

**Author:** ![rafael.guerra](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rafael.guerra/32/216610_2.png) [@rafael.guerra](https://discourse.julialang.org/u/rafael.guerra)\
**Post date:** [April 28, 2023, 4:20pm UTC](https://discourse.julialang.org/t/computation-termination/98046/5 "2023-04-28T16:20:44Z")

</div>

Why is it not possible to define a method for `f`?

```julia
f(x::Nothing) = nothing

```

---

<div class="post-metadata">

**Author:** ![mst](https://avatars.discourse-cdn.com/v4/letter/m/e0b2c6/32.png) [@mst](https://discourse.julialang.org/u/mst)\
**Post date:** [April 28, 2023, 4:24pm UTC](https://discourse.julialang.org/t/computation-termination/98046/6 "2023-04-28T16:24:34Z")

</div>

Throwing an exception indeed does the job; problem is, it seems a hacky solution to me, because – in my case – it is not an exception as such: it prints and ugly `Error` message and its backtrace (though the backtrace can be supressed). I am looking for a “cleaner” solution without an error message, that can be misleading for users.

---

<div class="post-metadata">

**Author:** ![mst](https://avatars.discourse-cdn.com/v4/letter/m/e0b2c6/32.png) [@mst](https://discourse.julialang.org/u/mst)\
**Post date:** [April 28, 2023, 4:27pm UTC](https://discourse.julialang.org/t/computation-termination/98046/7 "2023-04-28T16:27:41Z")

</div>

Because I’m lazy and want to avoid creating a bunch of methods that seem superfluous.

BTW, this is perhaps what I’ll end up doing – in spite of my laziness.

---

<div class="post-metadata">

**Author:** ![mst](https://avatars.discourse-cdn.com/v4/letter/m/e0b2c6/32.png) [@mst](https://discourse.julialang.org/u/mst)\
**Post date:** [April 28, 2023, 5:02pm UTC](https://discourse.julialang.org/t/computation-termination/98046/8 "2023-04-28T17:02:51Z")

</div>

or at least, is there a way the edit the `Error` string in the `throw` function to something less aggressive? say `Info`

---

<div class="post-metadata">

**Author:** ![sijo](https://avatars.discourse-cdn.com/v4/letter/s/da6949/32.png) [@sijo](https://discourse.julialang.org/u/sijo)\
**Post date:** [April 28, 2023, 6:36pm UTC](https://discourse.julialang.org/t/computation-termination/98046/9 "2023-04-28T18:36:32Z")

</div>

I don’t think so: an uncaught exception is an error. But you can catch the expression with a `try` block, and then you can print the message you want (or do nothing).

Could you give a full, concrete example of the behavior you want?

---

<div class="post-metadata">

**Author:** ![Henrique\_Becker](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/henrique_becker/32/15443_2.png) [@Henrique\_Becker](https://discourse.julialang.org/u/Henrique_Becker)\
**Post date:** [April 28, 2023, 7:07pm UTC](https://discourse.julialang.org/t/computation-termination/98046/10 "2023-04-28T19:07:49Z")

</div>

`f(x::Nothing) = nothing` is not superfluous, if it is the difference between `f(g(x))` being correct code or not. If you do not want the write the definition because it can be abused, and instead treat it at the call site, for many different kinds of single-argument functions, then you can define something like:

```julia
allow_nothing(f) = (x -> isnothing(x) ? nothing : f(x))

```

to use at the places you call the functions. Or you can create a macro alternative that _defines_ a method for you with similar behavior (but without the overhead of a closure) and invoke the macro for all functions (but as this is already single-line, I believe it is basically the same amount of effort).

---

<div class="post-metadata">

**Author:** ![mst](https://avatars.discourse-cdn.com/v4/letter/m/e0b2c6/32.png) [@mst](https://discourse.julialang.org/u/mst)\
**Post date:** [April 28, 2023, 8:51pm UTC](https://discourse.julialang.org/t/computation-termination/98046/11 "2023-04-28T20:51:45Z")

</div>

> [@sijo](#):
>
> Could you give a full, concrete example of the behavior you want?

My case is quite involved, so I’ll formulate something simpler.

> [@sijo](#):
>
> I don’t think so: an uncaught exception is an error. But you can catch the expression with a `try` block, and then you can print the message you want (or do nothing).

I can catch the expression and print something but it still returns `nothing`, which `f` receives and throws the method error.

---

<div class="post-metadata">

**Author:** ![mst](https://avatars.discourse-cdn.com/v4/letter/m/e0b2c6/32.png) [@mst](https://discourse.julialang.org/u/mst)\
**Post date:** [April 28, 2023, 9:16pm UTC](https://discourse.julialang.org/t/computation-termination/98046/12 "2023-04-28T21:16:10Z")

</div>

I think that the solution is what you said @sijo: throw an exception. I found a way [how to suppress the backtrace](https://discourse.julialang.org/t/a-julia-equivalent-to-rs-stop/36568/13) that produces a clean output; I only need to figure how to change/suppress the ugly red `Error` message tag. I looked into the `throw` code but it’s quite cryptic to me (I’m still sort of a julia neophyte) so I cannot replace that pesky error tag string. At least this solution does what I’m looking for; perhaps I should be content with that.

---

<div class="post-metadata">

**Author:** ![mst](https://avatars.discourse-cdn.com/v4/letter/m/e0b2c6/32.png) [@mst](https://discourse.julialang.org/u/mst)\
**Post date:** [April 28, 2023, 9:24pm UTC](https://discourse.julialang.org/t/computation-termination/98046/13 "2023-04-28T21:24:20Z")

</div>

This elides the red `Error` word:

```julia
Base.showerror(io::IO, e::ResponseException, bt; backtrace=true) = print(io, "\b"^7 * e.msg)

```

Does the job, but it’s horrid! The signature of a true noob.

---

<div class="post-metadata">

**Author:** ![sijo](https://avatars.discourse-cdn.com/v4/letter/s/da6949/32.png) [@sijo](https://discourse.julialang.org/u/sijo)\
**Post date:** [May 1, 2023, 7:31am UTC](https://discourse.julialang.org/t/computation-termination/98046/14 "2023-05-01T07:31:33Z")

</div>

I’d love to see a minimal working example of the thing you’re trying to achieve. It doesn’t have to be a real-life example, but some small working code that shows the behavior you want for functions `f` and `g`.

---

<div class="post-metadata">

**Author:** ![mst](https://avatars.discourse-cdn.com/v4/letter/m/e0b2c6/32.png) [@mst](https://discourse.julialang.org/u/mst)\
**Post date:** [May 1, 2023, 11:29pm UTC](https://discourse.julialang.org/t/computation-termination/98046/15 "2023-05-01T23:29:11Z")

</div>

Here it goes:

```julia
struct MyException <: Exception
    msg::AbstractString
end

function Base.showerror(io::IO, e::MyException, bt; backtrace=true)
    print(io, "\b"^7)
    print(io, e.msg)
end

f(x::Real) = x^2

function h(x)
    if isa(x, Real)
        x
    else
        e = MyException("This is not an error, I just want to terminate execution.")
        throw(e)
    end
end

```

Now test.

1. Valid:

```julia
julia> f(h(1))
1

```

1. Invalid:

```julia
julia> f(h("one"))
This is not an error, I just want to terminate execution.

```

which is what I was looking for: terminate execution to avoid a `f`’s method error.

---

<div class="post-metadata">

**Author:** ![jling](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jling/32/212909_2.png) [@jling](https://discourse.julialang.org/u/jling)\
**Post date:** [May 2, 2023, 1:10am UTC](https://discourse.julialang.org/t/computation-termination/98046/16 "2023-05-02T01:10:19Z")

</div>

> [@mst](#):
>
> which is what I was looking for: terminate execution to avoid a `f`’s method error.

return `nothing` is THE way to terminate execution of a function early.

If you use `return nothing` for something else, make your own signeton type and return that thing.

---

<div class="post-metadata">

**Author:** ![mst](https://avatars.discourse-cdn.com/v4/letter/m/e0b2c6/32.png) [@mst](https://discourse.julialang.org/u/mst)\
**Post date:** [May 2, 2023, 1:43am UTC](https://discourse.julialang.org/t/computation-termination/98046/17 "2023-05-02T01:43:44Z")

</div>

Indeed, but the whole point is to avoid defining an `f(x::Nothing)` method.

---

<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:** [May 2, 2023, 2:00am UTC](https://discourse.julialang.org/t/computation-termination/98046/18 "2023-05-02T02:00:37Z")

</div>

Am I correct in saying you want something like R’s [`stop`](https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/stop) function.  
Which terminates execution and returns to the top-level prompt without showing an big scary error message and stacktrace?

We have definitely talked about that before.  
At least once,

> [@A Julia equivalent to R's stop()?](https://discourse.julialang.org/t/a-julia-equivalent-to-rs-stop/36568):
>
> Is there an equivalent in Julia to the stop() function in R? The nice thing about stop() is that it can be run from any scope (e.g. a function within a function) and it will throw an error and terminate the function that the user called. I see that throw() in Julia does something similar, but I’d like to avoid printing a stack trace because it is not necessary for the info I’m trying to convey to users (e.g. two arrays provided as arguments are not the same size, but they need to be) For now, …

---

<div class="post-metadata">

**Author:** ![sijo](https://avatars.discourse-cdn.com/v4/letter/s/da6949/32.png) [@sijo](https://discourse.julialang.org/u/sijo)\
**Post date:** [May 2, 2023, 9:35am UTC](https://discourse.julialang.org/t/computation-termination/98046/19 "2023-05-02T09:35:08Z")

</div>

> [@mst](#):
>
> ```julia
> Base.showerror(io::IO, e::ResponseException, bt; backtrace=true) = print(io, "\b"^7 * e.msg)
> 
> ```
> 
> Does the job, but it’s horrid! The signature of a true noob.

I don’t know… this actually seems like a good solution for what you’re trying to do. BUT I suspect you’re trying to do something that’s wrong: calling `h` with a bad `x` value is an error and it’s wrong to pretend otherwise. If a user calls `f1` that calls `f2` that calls `f3` that calls `f` and all they get is the message `Computation interrupted (this is not an error)`, they will have a hard time finding the root of the problem.

Or maybe this `x` is not really a bad value? It’s a valid value that means “interrupt all computations”? I don’t remember seeing a real-life case where this makes sense. It sounds more like a recipe for [spaghetti code](https://en.wikipedia.org/wiki/Spaghetti_code): you have an inner function call that short-circuits all the caller functions as part of normal program execution (not error)? It’s like a `goto` but even worse because it’s not explicit.

To stay sane and avoid spaghetti code, when you write `f(g(x))` you normally want `g` to do its own job without interferring with the callers, and `f` should decide itself if it wants to interrupt its own computation depending on the return value of `g` (and `f` can include a `try-catch` block if it knows that `g` can throw an exception that `f` can handle itself).

(Of course maybe your thing actually does make sense and then I’d be curious to understand it better…)
