Language: Syntax catching multiple exceptions in a single on block

Created on 28 Nov 2018  路  3Comments  路  Source: dart-lang/language

In many cases I only care what type of exception I'm getting.
I don't care about the exception at-most I might want to do a e.toString().

Example:

for (int i = 0; i < retries; i++) {
  try {
    return networkOperation().timeout(Duration(seconds: 5));
  } on SocketException, TimeoutException {
    continue;
  }
}

This isn't critical at all, I was just surprised it didn't work already.

It's trivial to duplicate the block handling the exception, or write a function that accepts a list of types to ignore.

Please close if there is some complication to this that I don't see :)

request

Most helpful comment

If you look at this more generally, a catch clause:

  • Tests an object against some type (the on clause).
  • If the object has that type, optionally bind a new variable for the object (the catch clause).
  • Conditional executes some code where that variable is in scope (the catch block).

That's really similar to how pattern matching works in languages that have that. Most of those languages have some kind of | pattern that lets you concatenate multiple patterns together.

We're considering adding tuples to Dart, and those almost always lead to some kind of pattern matching syntax in order to destructure the fields back out of the tuple. If we do that, one solution for the problem here would be to extend to catch clauses to allow arbitrary patterns. If we have some kind of "or" pattern, that would then let you have a single catch clause that matches objects of multiple types.

All 3 comments

Being able to catch multiple exception in one block is really useful in my opinion to avoid duplication of code or noise on error management

If you look at this more generally, a catch clause:

  • Tests an object against some type (the on clause).
  • If the object has that type, optionally bind a new variable for the object (the catch clause).
  • Conditional executes some code where that variable is in scope (the catch block).

That's really similar to how pattern matching works in languages that have that. Most of those languages have some kind of | pattern that lets you concatenate multiple patterns together.

We're considering adding tuples to Dart, and those almost always lead to some kind of pattern matching syntax in order to destructure the fields back out of the tuple. If we do that, one solution for the problem here would be to extend to catch clauses to allow arbitrary patterns. If we have some kind of "or" pattern, that would then let you have a single catch clause that matches objects of multiple types.

Related link.

Was this page helpful?
0 / 5 - 0 ratings