Menu
Coddy logo textTech

Handling Conversion Errors

Part of the Fundamentals section of Coddy's Dart journey — lesson 86 of 94.

The tryParse method safely converts strings to numbers, returning null instead of throwing an error when conversion fails.

Use tryParse instead of parse for safer conversion:

String validNumber = "42";
int? result = int.tryParse(validNumber);
print(result);

After executing the above code, the output will be:

42

When conversion fails, tryParse returns null:

String invalidNumber = "hello";
int? result = int.tryParse(invalidNumber);
print(result);

After executing the above code, the output will be:

null
challenge icon

Challenge

Beginner

In this challenge, you'll practice using tryParse to safely convert strings to numbers. The tryParse method returns null if the conversion fails, instead of throwing an error like parse does.

Complete the code to convert the string userInput to an integer using int.tryParse(). If the conversion is successful, store the result in userAge. If the conversion fails (returns null), use the default age of 0.

Expected output for the current input:

Invalid age input. Using default age: 0

Cheat sheet

The tryParse method safely converts strings to numbers, returning null instead of throwing an error when conversion fails.

Use tryParse for safe string to number conversion:

String validNumber = "42";
int? result = int.tryParse(validNumber);
print(result); // Output: 42

When conversion fails, tryParse returns null:

String invalidNumber = "hello";
int? result = int.tryParse(invalidNumber);
print(result); // Output: null

Try it yourself

void main() {
  // This string is already defined for you
  String userInput = 'twenty five';
  
  // TODO: Try to convert userInput to an integer using int.tryParse()
  // If successful, store the result in userAge
  // If conversion fails (returns null), use the default age of 0
  int userAge = 0;
  
  // Display the result
  if (userInput == 'twenty five') {
    print('Invalid age input. Using default age: $userAge');
  } else {
    print('Valid age input: $userAge');
  }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals