How to use the finally keyword in Dart
Overview
The finally keyword is used in the try-catch block. The finally block is executed regardless of whether an exception occurs.
Syntax
try {
// code that might throw an exception
}
.
.
.
finally {
// The code will be executed irrespective of the exception
}
Code
The following code shows how to use the finally keyword in Dart:
main() {int x = 20;int result;// try-catch blocktry {result = x ~/ 0;}catch (e) {print('Type of Exception: ${e}');}finally {print('The Finally block is executed');}}
Explanation
- Line 1–14: We create the
main()function. - Line 2–3: In
main(), we declare two variables of int type,x = 20andresult. - Line 5: We wrap the code with a
try-catchblock to catch any errors. - Line 6: We assign the result from the computation
(x~/0)toresult. - Line 8–10: We use
catchto catch any exception types that occurs. - Line 11–13: We execute the
finallyblock, irrespective of the exception that occurs.