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:
42When conversion fails, tryParse returns null:
String invalidNumber = "hello";
int? result = int.tryParse(invalidNumber);
print(result);After executing the above code, the output will be:
nullChallenge
BeginnerIn 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: 0Cheat 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: 42When conversion fails, tryParse returns null:
String invalidNumber = "hello";
int? result = int.tryParse(invalidNumber);
print(result); // Output: nullTry 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');
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Comparison OperatorsLogical ANDLogical ORLogical NOTType Test OperatorsRecap - Making Comparisons7Working with Strings
String ConcatenationString InterpolationMulti-line StringsString PropertiesBasic String Methods10Collections - Maps Basics
What are Maps?Creating a MapAccessing Values by KeyKey-Value PairsGetting Map SizeGetting KeysGetting ValuesChecking if a Key Exists13Null Safety In Depth
Understanding NullNullable TypesNon-Nullable TypesNull Assertion OperatorLate InitializationRecap - Handling Null Safely16Fundamentals Challenges
Challenge: List of calculationChallenge: Sum of numbersChallenge: Find product2Variables and Basic Data Types
What are Variables?StringsIntegers (int)Doubles (double)Booleans (bool)Type Inference with 'var'Final VariablesConstant VariablesNaming ConventionsBasic Null SafetyRecap - Declaring Variables8Control Flow - Loops
The 'for' LoopThe 'while' LoopThe 'do-while' LoopUsing 'break' in LoopsUsing 'continue' in LoopsRecap - Repeating Code11Functions Basics
What are Functions?Defining a Basic FunctionCalling a FunctionFunctions with ParametersFunctions Returning ValuesThe 'void' KeywordArrow SyntaxRecap - Simple Functions14Type Conversion
Converting String to intConverting String to doubleConverting Numbers to StringHandling Conversion Errors3Operators Part 1
Arithmetic OperatorsInteger DivisionModulo OperatorIncrement and DecrementAssignment ShortcutsRecap - Simple Calculations6Control Flow - Decision Making
The 'if' StatementThe 'else' StatementThe 'else if' StatementRecap - Simple DecisionsNested 'if' StatementsThe 'switch' Statement9Collections - Lists Basics
What are Lists?Creating a ListAccessing by IndexGetting List LengthAdding ElementsRemoving ElementsChecking if a List is EmptyIterating Over a List12Functions Advanced
Optional Positional ParametersNamed ParametersRequired Named ParametersDefault Parameter ValuesRecap - Function Parameters15Project: Simple Calculator
Setting UpDeclaring Number