What is the catch keyword in Dart?
Overview
In Dart, we use the catch keyword alongside the try block to catch program exceptions.
We use the catch block when we require the exception object.
Syntax
try {
// The program that might throw an exception
}
catch Exception1 {
// The code for handling exception 1
}
Code example
The following code shows how to use the catch keyword in Dart:
void main() {try {// Declare variables x and yint x = 5, y;y = x ~/ 0;}catch (e){print("Error: $e");}}
Explanation
- Line 1: 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 typex = 5andy. - Line 5: We assign the result from the computation
(x~/0)toy. - Line 8: We use
catchto catch any exception that occurs.