Menu
Coddy logo textTech

Catching Exceptions with 'on'

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

While the basic try-catch block catches any exception that occurs, sometimes you need to handle different types of exceptions in different ways. The on keyword allows you to catch specific exception types and provide tailored responses for each.

Instead of catching all exceptions with a generic catch, you can target specific exceptions using on followed by the exception type. This gives you more control over how your program responds to different error situations.

try {
  int number = int.parse("abc");
} on FormatException {
  print("Please enter a valid number");
}

In this example, the code specifically catches a FormatException, which occurs when trying to parse invalid text as a number. This allows you to provide a clear, user-friendly message that directly addresses the problem, rather than showing a generic error message that might confuse users.

You can also combine multiple on blocks to handle different exception types with appropriate responses, making your error handling both precise and user-friendly.

challenge icon

Challenge

Easy

Create a program that demonstrates catching specific exceptions using the on keyword. Your program will process different types of user inputs and handle specific exception types with tailored error messages.

  1. Read a string input representing a mathematical expression type ("parse", "divide", or "access")
  2. Read a string input representing the first value
  3. Read a string input representing the second value (when applicable)
  4. Based on the expression type, perform the corresponding operation using specific exception handling:
    • For "parse": Convert the first value to an integer using int.parse() and catch FormatException specifically
    • For "divide": Parse both values as integers and perform division, catching FormatException for parsing errors
    • For "access": Create a list with the first value and access the index specified by the second value, catching RangeError for invalid indices
  5. Display the results or specific error messages in the exact format shown below

For example, if the inputs are "parse", "42", "unused", your program should output:

Operation: parse
Input: 42
Parsing successful!
Result: 42

If the inputs are "parse", "xyz", "unused", your program should output:

Operation: parse
Input: xyz
FormatException caught: Invalid number format
Please provide a valid integer

If the inputs are "divide", "10", "2", your program should output:

Operation: divide
Values: 10, 2
Division successful!
Result: 5

If the inputs are "divide", "10", "abc", your program should output:

Operation: divide
Values: 10, abc
FormatException caught: Invalid number format
Cannot perform division with invalid numbers

If the inputs are "access", "hello", "1", your program should output:

Operation: access
List: [hello]
Index: 1
RangeError caught: Index out of range
Valid indices are 0 to 0

Your program must use separate try-catch blocks with the on keyword to catch FormatException and RangeError specifically. Each exception type should have its own tailored error message that clearly explains what went wrong. For the "access" operation, create a list containing only the first input value and attempt to access the index specified by the second input value.

Cheat sheet

Use the on keyword to catch specific exception types instead of using a generic catch block:

try {
  int number = int.parse("abc");
} on FormatException {
  print("Please enter a valid number");
}

You can combine multiple on blocks to handle different exception types with appropriate responses:

try {
  // some code that might throw different exceptions
} on FormatException {
  print("Invalid format error");
} on RangeError {
  print("Index out of range error");
}

This approach provides more control over error handling by allowing tailored responses for each specific exception type.

Try it yourself

import 'dart:io';

void main() {
  // Read input
  String? operation = stdin.readLineSync();
  String? firstValue = stdin.readLineSync();
  String? secondValue = stdin.readLineSync();
  
  // Display operation info
  print('Operation: $operation');
  
  // TODO: Write your code below
  // Use try-catch blocks with 'on' keyword to handle specific exceptions
  // Handle FormatException for parse and divide operations
  // Handle RangeError for access operation
  
}
quiz iconTest yourself

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

All lessons in Logic & Flow