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 yint 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
tryblock to catch any error. - Line 4: In
main(), we declare two variables of int type,x = 5andy. - Line 5: We assign the result from the computation
(x~/0)toy. - Line 8: We use
onto specify the exception type that occurs.