When developing a ruby console application in Ruby, you may encounter a problem: You can use Ctrl + C to stop the running program.
If no control is added, the program is aborted and an error stack is printed.
For example, the following program:
Cmd = Nil
While cmd !~ /Y | n | N/
Print "continue? (Y/N ):"
Cmd = stdin. Gets
Cmd. chomp!
End
If cmd = ~ /Y | Y/then
Puts "continue ."
Else
Puts "exit ."
End
When running, CTRL + C is interrupted, the screen displays:
Continue? (Y/N): e:/projectruby/03 _ Getting Started without opening/06_source/testru
Nner/tester. RB: 48: In 'gets': interrupt
From E:/projectruby/03 _ Getting Started without opening/06_source/testrunn
ER/tester. RB: 48
In order to prevent the interruption information from causing bad prompts to users, the program should handle this situation,
The user's Ctrl + C will throw an interrupt exception at the ruby underlying layer, so you can capture this exception through begin... rescue... end.
Begin
Cmd = Nil
While cmd !~ /Y | n | N/
Print "continue? (Y/N ):"
Cmd = stdin. Gets
Cmd. chomp!
End
If cmd = ~ /Y | Y/then
Puts "continue ."
Else
Puts "exit ."
End
Rescue interrupt
Puts "programme is interrupted ."
End
When running, CTRL + C is interrupted, the screen displays:
Continue? (Y/N): Programme is interrupted.
This prevents user confusion caused by stack information.
The PS: kernal: exit command throws a systemexit exception.