Subject: | (Discussion) Exception dispatch |
While this module clearly is designed to work like the try/catch/finally syntax in many other languages, exception dispatch in 'catch' is a more complex topic in Perl and thus not implemented yet. I am collecting here the current discussion and my thoughts so far.
1. The usual expected syntax based on object- and type-heavy languages is:
catch (ExceptionClass $e) { ... }
TryCatch, Syntax::Feature::Try, Error, and Try::Tiny::ByClass support this sort of dispatch. This could also be done here, but they don't use any common dispatch mechanism other than ->isa (mostly since they are quite different in underlying implementation). Additionally, in Perl, unlike most languages that make this feature popular, exceptions are commonly also bare strings.
2. Bare strings could be dispatched by providing a regex:
catch (qr/.../ $e)
But that looks kind of weird compared to the typed dispatch.
3. It could instead take less magical class-name strings or regexes:
catch ('ExceptionClass') { ... }
catch (qr/.../) { ... }
This could use $@ directly like a normal catch block, or a lexical could be provided by a separate part of the syntax, like:
catch ('ExceptionClass') as $e { ... }
4. Dispatch could also be done by smartmatching on provided type objects with smartmatch overload. This would be very similar to Function::Parameters types for example.
use Types::Standard 'Int', 'InstanceOf';
catch (Int $e) { ... }
catch (InstanceOf['ExceptionClass'] $e) { ... }
However, exceptions are always strings or references, so a lot of the types are useless, and I don't see any value in making the common useful cases more complicated, just to be able to dispatch to hashref or arrayref or other weird exceptions. On the other hand, it would make this possible automatically:
catch (InstanceOf['ExceptionClass', 'OtherClass']) { ... }
5. TryCatch provides an additional mechanism where you can provide an arbitrary boolean expression, but this also seems unnecessary for the majority of cases and adds some syntax confusion.
catch (ExceptionClass $e where { $_->is_wobbly })
6. Regardless of syntax, there is no way to allow an exception to propagate from the original exception context if conditional `catch` blocks are provided and it does not match any of them. This means it would have to require that a non-conditional `catch` block is also present, or otherwise differ from the usual semantics which goes against what this module is trying to do.