How to run a final function when either program fails or user crtl + c?

Hello!

I was wondering if there was some way to run a final function when either the program fails due to for example division by zero or when an user chooses to terminate a program?

The first bit, running something when a program fails I believe I could do with a try-catch-finally loop, but what about the crtl + c part?

Kind regards

Depending on whether you are running Julia interactively, Ctrl-C produces an InterruptException which can be caught like any other. This behaviour can be changed with Base.exit_on_sigint.

Alternatively, you can register a function using atexit.

Could you point me to a small example for Base.exit_on_sigint?

I am new to handling crtl + c events and exit in general. atexit did not seem to work for me, since it is only triggered when exciting Julia completely, while crtl + c just stops the currently running code.

Kind regards

If you are running in a Julia REPL (which I’m guessing you’re doing as ctrl+c isn’t exiting completely) then you don’t need to set Base.exit_on_sigint. But you can get help with ?Base.exit_on_sigint in the REPL.

For example, a simple try/catch works for me like this:

julia> try
         sleep(5.0)
       catch
         println("Hello")
       end
^CHello

If you’re running a script using julia <filename> then you’ll need

Base.exit_on_sigint(false)
try
  sleep(5.0)
catch
  println("Hello")
end

which produces

$ julia script.jl
^CHello
2 Likes