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 y
int 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 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 catch to catch any exception that occurs.

Free Resources