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 block
try {
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 = 20 and result.
  • Line 5: We wrap the code with a try-catch block to catch any errors.
  • Line 6: We assign the result from the computation (x~/0) to result.
  • Line 8–10: We use catch to catch any exception types that occurs.
  • Line 11–13: We execute the finally block, irrespective of the exception that occurs.

Free Resources