如何实现异常的默认行为?begin rescue else
不起作用(我认为应该).
并且,else
在场景中没有意义吗?在没有引发异常时必须运行的任何代码都在begin-rescue
块之间运行.
顺便说一下,我有以下解决方法,但我对此并不满意.
class MyException < Exception
end
class YourException < Exception
end
begin
raise MyException if 2 > 50
raise YourException if 1 < 90
rescue Exception => e
case e.message
when /MyException/
puts "MyException Caught"
else
puts "Default Exception Caught"
end
end
Run Code Online (Sandbox Code Playgroud)
首先,你真的不应该是子类Exception
.它的超类所有的Ruby异常,其中包括NoMemoryError
,SyntaxError
,Interrupt
,SystemExit
,所有这些你通常不需要拯救.不管是意外还是故意这样做都是不鼓励的,因为它可以防止程序正常退出,即使它被用户中断也是如此.它还可以隐藏或产生一些非常模糊的错误.
您想要子类化的是StandardError
,这是我们在日常编程中看到的大多数Ruby错误的超类.rescue
如果你不指定一个类,那么这个类也是d:
begin
object.do_something!
rescue => error # will rescue StandardError and all subclasses
$stderr.puts error.message
end
Run Code Online (Sandbox Code Playgroud)
我相信这是你正在寻找的"默认行为".您可以处理特定错误,然后处理所有其他错误:
class CustomApplicationError < StandardError
end
begin
object.do_something!
rescue CustomApplicationError => error
recover_from error
rescue => error
log.error error.message
raise
end
Run Code Online (Sandbox Code Playgroud)
该else
句在错误处理中毫无意义.当且仅当没有引发异常时,它将执行嵌套代码,而ensure
不管是否执行代码的子句.它允许您处理成功案例.
begin
object.do_something!
rescue => error
log.error error.message
else
log.info 'Everything went smoothly'
end
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
198 次 |
最近记录: |