Menu
Coddy logo textTech

The 'try-catch' Block

Part of the Logic & Flow section of Coddy's Dart journey — lesson 39 of 65.

Now that you understand what exceptions are, let's learn how to handle them gracefully using the try-catch block. This is the fundamental tool that prevents your program from crashing when something goes wrong.

The try-catch block works by wrapping potentially problematic code in a try section. If an exception occurs, instead of crashing your program, Dart immediately jumps to the catch section where you can handle the error appropriately.

try {
  // Code that might cause an exception
  int number = int.parse("abc");
} catch (e) {
  // Code that runs if an exception occurs
  print("Something went wrong: $e");
}

In this example, trying to convert the string "abc" to an integer would normally crash your program. However, because it's wrapped in a try block, the exception is caught and handled in the catch block instead. The variable e contains information about what went wrong.

This approach allows your program to continue running even when unexpected situations occur, making your code much more robust and user-friendly.

challenge icon

Challenge

Easy

Create a program that safely converts user input strings to numbers using a try-catch block. Your program should handle cases where the input might not be a valid number and prevent the program from crashing.

  1. Read a string input that represents a number that needs to be converted to an integer
  2. Use a try-catch block to safely attempt the conversion using int.parse()
  3. If the conversion is successful, calculate the square of the number (multiply it by itself)
  4. If the conversion fails and an exception occurs, handle the error gracefully
  5. Display the appropriate result or error message in the exact format shown below

For example, if the input is "5", your program should output:

Processing input: 5
Conversion successful!
The square of 5 is: 25

If the input is "abc", your program should output:

Processing input: abc
Error: Cannot convert 'abc' to a number
Please enter a valid integer

If the input is "12", your program should output:

Processing input: 12
Conversion successful!
The square of 12 is: 144

Your program must use a try-catch block to wrap the int.parse() operation. In the try section, attempt to convert the input string to an integer and calculate its square. In the catch section, handle any exception that occurs during the conversion and display an appropriate error message. The program should continue running normally regardless of whether the conversion succeeds or fails.

Cheat sheet

Use try-catch blocks to handle exceptions gracefully and prevent program crashes:

try {
  // Code that might cause an exception
  int number = int.parse("abc");
} catch (e) {
  // Code that runs if an exception occurs
  print("Something went wrong: $e");
}

The try block contains potentially problematic code, while the catch block handles any exceptions that occur. The variable e contains information about the exception.

Try it yourself

import 'dart:io';

void main() {
  // Read input string
  String? input = stdin.readLineSync();
  
  // Display processing message
  print('Processing input: $input');
  
  // TODO: Write your code below
  // Use try-catch block to safely convert the input to integer
  // Calculate the square if conversion is successful
  // Handle any exceptions that occur during conversion
  
}
quiz iconTest yourself

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

All lessons in Logic & Flow