Felix Schütz
Felix Schütz

Reputation: 1377

Catch multiple specific exception types in Dart with one catch expression

I know I can catch a specific Exception type in dart with the following:

try {
  ...
} on SpecificException catch(e) {
  ...
}

But is there a way to catch multiple specific exception types with on line instead of using multiple catch statements?

Upvotes: 56

Views: 22126

Answers (3)

Chuck Batson
Chuck Batson

Reputation: 2764

It is perhaps worth noting that exceptions of different type but with common ancestry can be caught by a single on statement. For example

abstract class A implements Exception {}

class B implements A {}

class C implements A {}

void main() {
  try {
    throw B();
  }
  on A {
    print('caught B using on A');
  }
  try {
    throw C();
  }
  on A {
    print('caught C using on A');
  }
}

which outputs

caught B using on A
caught C using on A

Upvotes: 2

Moacir Schmidt
Moacir Schmidt

Reputation: 935

No, there isn't, but you can do this:

try {
  ...
} catch (e) {
  if (e is A || e is B) {
    ...
  } else {
    rethrow;
  }
}

Upvotes: 36

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657238

You can only specify one type per on xxx catch(e) { line or alternatively use catch(e) to catch all (remaining - see below) exception types. The type after on is used as type for the parameter to catch(e). Having a set of types for this parameter wouldn't work out well.

try {
  ...
} on A catch(e) {
  ...
} on B catch(e) {
  ...
} catch(e) { // everything else
}

Upvotes: 88

Related Questions