0

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 rescues 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?

Aetherus
  • 8,720
  • 1
  • 22
  • 36
  • 1
    Do you really want to create such a class or do you want to create a way to exit a loop? – Dominik Sandjaja Nov 11 '16 at 09:10
  • Okay. The need is to halt a database stream handling and close the stream when some condition is met. For some reason, the handler method is of type `void` and I just can't tell the lib to `break` its loop. – Aetherus Nov 11 '16 at 09:17
  • You could extend `RuntimeException` (http://docs.oracle.com/javase/8/docs/api/java/lang/RuntimeException.html) which is unchecked. But ultimately it needs to be caught, which you seem to be planning to do anyway. – d.j.brown Nov 11 '16 at 09:18
  • @d.j.brown I need a `Throwable` that's not an `Exception` because the lib simply catches all exceptions and wraps them in its own exception class then re-throws them. – Aetherus Nov 11 '16 at 09:20
  • 1
    @Aetherus I don't think this is possible "For the purposes of compile-time checking of exceptions, `Throwable` and any subclass of `Throwable` that is not also a subclass of either `RuntimeException` or `Error` are regarded as checked exceptions." and "Only objects that are instances of this class [`Throwable`] (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java `throw` statement" (http://docs.oracle.com/javase/8/docs/api/java/lang/Throwable.html) – d.j.brown Nov 11 '16 at 09:22
  • 1
    Now I feel it was a wrong decision to not bring `goto` to Java :) – Aleksei Matiushkin Nov 11 '16 at 09:42

0 Answers0