Full disclosure: my entire experience with Dart is the 2 minutes I just spent reviewing the syntax of its try
statement. This is based solely on a observation about Python's semantics.
What does else
do in Python?
Skip to the end of the answer for the suggested Dart code.
The following two pieces of code are very similar in Python:
try:
...
<last code>
except SomeError:
...
finally:
...
and
try:
...
except SomeError:
...
else:
<last code>
finally:
...
<last code>
will be executed in the same circumstances in both. The difference is that any exceptions raised by <last statement>
will be caught in the first, but not in the second.
Simulating else
in Python
To simulate else
's semantics in Python, you would use an additional try
statement and a flag to indicate if an exception should be rethrown.
else_exception = False
try:
...
try:
<last code>
except Exception as e:
else_exception = True
except SomeError:
...
finally:
if else_exception:
raise e
...
We check if the nested try
caught an exception in the finally
clause, since the else
clause would have executed before anything else in finally
. If there was an exception, reraise it now that it won't be immediately caught, just as in the else
. Then you can proceed with the rest of finally
.
Simulating else
in Dart
As far as I can tell, the same logic would be necessary in Dart.
bool else_exception = false;
try {
...
try {
<last code>
} catch (e) {
else_exception = true;
}
} on SomeError catch (e) {
...
} finally {
if (else_exception) {
throw e;
}
...
}
Note that if <last code>
throws an exception, the above code will not properly preserve the stacktrace. To do that, some more care would be needed:
bool else_exception = false;
try {
...
try {
<last code>
} catch (e) {
else_exception = true;
rethrow;
}
} on SomeError catch (e) {
if (else_exception) {
rethrow;
}
...
}