问题
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