The Crystal Programming Language Forum

Rescue as a suffix

AFAIK, inline (or suffix) rescue does not seem to be documented.

Yet, the following code works :

def quit(msg)
  puts msg
  puts "exiting 1"
end
 
td1 = Time.parse("2021-02-29", "%Y-%m-%d", Time::Location.local) rescue quit("Invalid date td1")
p! td1

and, even, to avoid a method def

td2 = Time.parse("2021-02-29", "%Y-%m-%d", Time::Location.local) rescue begin puts("Invalid date td2"); puts "exiting 1"; end
p! td2

Is it safe to use these forms ?

[Edit] : Exception data (message) is not available, however.

It seems documentation for trailing rescue is just missing. But it’s a part of the language and definitely safe to use.
However, I would recommend begin/rescue blocks instead for any kind of complex expressions. The following code is much easier to read and reason about than your example:

td2 = begin
  Time.parse("2021-02-29", "%Y-%m-%d", Time::Location.local)
rescue
  puts("Invalid date td2")
  puts "exiting 1"
end
p! td2
3 Likes