How to use the on keyword in Dart

The on keyword

In Dart, the on keyword is used with the try block when we have a certain type of exception to catch.

Syntax


try {
// some code here
}
on exception_type {
// some code here
}

Code

The following code shows how to use the on keyword in Dart:

void main() {
try {
// declare variable x and y
int x = 5, y;
y = x ~/ 0;
}
on IntegerDivisionByZeroException {
print("Error: Zero division");
}
}

Explanation

  • Lines 1–12: We create the main() function.
  • Line 2: We wrap the code within a try block to catch any error.
  • Line 4: In main(), we declare two variables of int type, x = 5 and y.
  • Line 5: We assign the result from the computation (x~/0) to y.
  • Line 8: We use on to specify the exception type that occurs.

Free Resources