What system signal is sent to the ruby ​​program when an exception occurs and the program stops execution?

At any time when my program stops execution (either when shutting down with cmd-c, or when an exception is detected), I want to take several actions to close normally.

When I do cmd-c, I get a TERM signal. What signal is sent when a program encounters an exception? How to do this with Signal.trap (...)?

+3
source share
5 answers

You can wrap your code in a block begin-ensure-end. It will catch exceptions and CTRL-C. (You can add a salvation offer before ensure).

begin
  sleep 10 #try CTRL-C here
  raise "kaboom" #RuntimeError
ensure
  puts "This must be printed no matter what."
end
+2
source

. Ruby ; .

, rescue.

+2

Signal.trap, , begin-rescue-end. , :

begin
  # here goes the code that may raise an exception
rescue ThisError
  # this code is executed when 'ThisError' was raised
rescue ThatError, AnotherError
  # this code is executed when 'ThatError' or 'AnotherError' was raised
rescue
  # this code is executed when any other StandardError was raised
else
  # this code is executed when NO exception was raised
ensure
  # this code is always executed
end

, :

def compute_something(x,y)
  raise ArgumentError, 'x must not be lower than 0' if x < 0
  x/y + y
end

begin
  compute_something(-10,5)
rescue ArgumentError
  puts "some argument is erroneous!"
end

puts "---"

x=100
y=0

begin
  compute_something(x,y)
rescue ZeroDivisionError
  puts "division by zero! trying to fix that..."
  y=1
  retry
else
  puts "everything fine!"
end

puts "---"

begin
  compute_something(1)
rescue => e
  puts "the following error occured:"
  puts e
end

puts "---"

begin
  exit
ensure
  puts "i am always called!"
end

:

some argument is erroneous!
---
division by zero! trying to fix that...
everything fine!
---
the following error occured:
wrong number of arguments (1 for 2)
---
i am always called!
+1

, - , 'EXIT':

Signal.trap('EXIT') do
  puts "Terminating..."
  shutdown()
end

, ; begin rescue.

+1
+1
source

All Articles