syntax for methods using raise / throw in Sorbet

北战南征 提交于 2020-01-16 09:08:23

问题


Is there a way to specify which exceptions a method might raise, so it's known for which a rescue might be needed?

 

In Java (Doc) it looks this way:

void example(int: x) throws Exception {
  if x > 42 throw new Exception;
}

 

Maybe something like this!?

→ View on sorbet.run

# typed: true
extend T::Sig

sig {params(x: Integer).void.raises(StandardError)}
def example(x)
  raise RuntimeError if x > 42
end

 

 

Don't get confused: Usual exceptions are handled using raise ... rescue in Ruby.

begin
  raise StandardError
rescue StandardError
end

But you can also throw objects and catch them in Ruby.

catch(:something) do
  throw :something
end

I don't use this a lot. Actually trying to avoid it totally. But Sorbet might also have a syntax for this!? E.g.:

→ View on sorbet.run

# typed: true
extend T::Sig

sig {params(x: Integer).void.throws(:something)}
def example(x)
  throw :something if x > 42
end

catch (:something) {example(42)}

回答1:


Sorbet does not support checked exceptions. The reason for that is that it's generally agreed between people working on Java today that they don't work well with other features of even Java. For example, in the snippet below

foo do
  # code that calls into something that can throw
end

In Java you are formally forced to catch exceptions inside # and rethrow them as unchecked one, as in general the block might escape to heap. Overall, if you look into languages that followed Java: Scala, Kotlin, neither of them supports checked exceptions.



来源:https://stackoverflow.com/questions/57454717/syntax-for-methods-using-raise-throw-in-sorbet

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!