Reputation: 1377
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
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
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
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