Julia, handle keyboard interrupt

Viewed 1462

Title says it all. How can I handle or catch a SIGINT in julia? From the docs I assumed I just wanted to catch InterruptException using a try/catch block like the following

try
    while true
        println("go go go")
    end
catch ex
    println("caught something")
    if isa(ex, InterruptException)
        println("it was an interrupt")
    end
end

But I never enter the catch block when I kill the program with ^C.

edit: The code above works as expected from the julia REPL, just not in a script.

3 Answers

For julia >= 1.5, there is Base.exit_on_sigint. From the docs (retrieved on 20220419)

Set exit_on_sigint flag of the julia runtime. If false, Ctrl-C (SIGINT) is capturable as InterruptException in try block. This is the default behavior in REPL, any code run via -e and -E and in Julia script run with -i option.

Related