How to stop script execution

Hi,

How can I stop script execution if certain condition is not met? exit() does not work here as it exit julia.

1 Like

I usually avoid scripts and pack things into functions. In that way I can gracefully return if a condition is met (or not). You can also break to exit for loops, without exiting the function that contains those for loops.
Hope this helps.

2 Likes

What do you mean by script and how did you run it? Did you mean including a file?

This thread might be helpful to you. It sounds like you are trying to do something similar.

1 Like

Hi @yuyichao

Sometimes conditions cannot be met by the input provided by the user. In this case, there is no point of continuing running the code, and I would rather exit with a message. I am looking for something similar to return in MATLAB.

Something like this?

function main()
    # code
    if break_condition
        return
    end
    # more code
end
main()

An other advantage is that this avoids global variables, which are bad for performance.

1 Like

I asked that on stack overflow once and there isn’t really a satisfactory solution to it, besides just throwing an error:

https://stackoverflow.com/questions/35226337/how-to-quit-exit-from-withing-included-file-file

That isn’t what I asked. The question is what you meant by “script execution”.

If you indeed mean by includeing a file, then no there’s no global control flow. You could throw an error to abort execution but you should just use a function instead.

I think that I understand the question from @hmemy
Java, Python, C/C++, Fortran, etc. provide a system function that will immediately exit to the resident operating system. Python: sys.exit(n). Java: System.exit(n). It doesn’t matter if the caller is the main program, a function, or an included module, whatever.

There are situations where this is useful. For example, a function (“oops”) is being called to tidy up (flush butters, close files etc.), println a clear application-specific message, and then exit to the O/S directly. Tracebacks serve no purpose in this case because the oops-function can fully communicate what the problem is without the distracting clutter of a traceback.

You can implement this yourself as exemplified:

function oops(msg::AbstractString)
    println("\n*** Oops, $msg\n")
    # close database, close files, .....
    ccall(:jl_exit, Cvoid, (Int32,), 86) # Exit code 86 to the O/S
end
1 Like

Or — at the risk of undercomplicating it — just exit(86).

4 Likes