I just wanna reimplement Ruby's catch-throw
structure in Java.
The catch-throw
structure is like
catch :halt do
loop do # an infinite loop
puts 'foo'
throw :halt
end
end
The message foo
is printed only once. The essence is that what you throw
is not an exception, so it survives all rescue
s and propagates the call stack until you catch
it.
In Java, I know there is the class java.lang.Throwable
which has two built-in subclasses java.lang.Exception
and java.lang.Error
. What I need is a custom class, say Halt
that directly inherits Throwable
, which means it's neither a common Exception
that could be caught by third-party libraries or frameworks, nor an Error
which may affect tests. Halt
needs to be non-checked so that I don't have to add throws Halt
in the method declarations or a forced try-catch
. How can I define such class?