Câu trả lời:
Phương thức "def" có thể dùng như một câu lệnh "begin":
def foo
...
rescue
...
end
do/ endkhối ký tự tạo thành các khối ngoại lệ ngầm định.
rescue TypeError; rescue NameError- hoặc bạn có thể phân tách các lớp ngoại lệ bằng dấu phẩy, ví dụrescue TypeError, NameError
Bạn cũng có thể giải cứu nội tuyến:
1 + "str" rescue "EXCEPTION!"
sẽ in ra "EXCEPTION!" vì 'Chuỗi không thể bị ép buộc vào Fixnum'
StandardErrorvà tất cả các lớp con của nó, như NameError- nghĩa là ngay cả một lỗi đánh máy trong mã của bạn cũng không gây ra lỗi .. Xem thinkbot.com/blog/don-t-inline-rescue-in- hồng ngọc .
Thí dụ:
begin
# something which might raise an exception
rescue SomeExceptionClass => some_variable
# code that deals with some exception
ensure
# ensure that this code always runs
end
Đây, defnhư một begintuyên bố:
def
# something which might raise an exception
rescue SomeExceptionClass => some_variable
# code that deals with some exception
ensure
# ensure that this code always runs
end