Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

dart
keyword
catch
communitycreator

What is the catch keyword in Dart?

Maria Elijah

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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");
}
}
Use of the catch keyword in Dart

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.

RELATED TAGS

dart
keyword
catch
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring