How to prevent Ctrl-C from terminating a program during readline()

Hi, the following simple code is my attempt to see if I can trap Ctrl-C during readline()

Say I’m writing a REPL for a simple language interpreter… obviously I don’t want user accidentally pressing Ctrl-C to cause program termination.

function enter()
    println("Enter a line:")
    try
        s = readline()
        println(s)
    catch ex
        if ex isa InterruptException
            println("Ctrl-C")
        else
            println("Other Exceptions")
        end
    end
end

enter()

But I find it is not able to get into the catch section.
When user presses Ctrl-C Julia exits… this output was from MacOS Catalina. (Julia on Unbuntu also cannot trap Ctrl-C but with a much lengthier stack trace):

$ julia test_readline.jl

Enter a line:
abcd^C

signal (2): Interrupt: 2
in expression starting at /Users/bryanso/GDrive/fun/julia/test_readline.jl:18
kevent at /usr/lib/system/libsystem_kernel.dylib (unknown line)
unknown function (ip: 0x0)
Allocations: 2508 (Pool: 2497; Big: 11); GC: 0

Would you mind giving me a hint on how to trap Ctrl-C so I can recover from it?

Thanks a lot.

Found this topic in FAQ!

But let me know if there are other ways.

How do I catch CTRL-C in a script?

Running a Julia script using “julia file.jl” does not throw InterruptException when you try to terminate it with CTRL-C (SIGINT). To run a certain code before terminating a Julia script, which may or may not be caused by CTRL-C, use atexit. Alternatively, you can use “julia -e ‘include(popfirst!(ARGS))’ file.jl” to execute a script while being able to catch InterruptException in the try block.

Starting with Julia 1.5 you will be able to add the following line to your enter function to get the desired behavior

Base.exit_on_sigint(false)

Thanks! Looking forward to using it.