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
EasyCreate 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.
- Read a string input representing a mathematical expression type (
"parse","divide", or"access") - Read a string input representing the first value
- Read a string input representing the second value (when applicable)
- Based on the expression type, perform the corresponding operation using specific exception handling:
- For
"parse": Convert the first value to an integer usingint.parse()and catchFormatExceptionspecifically - For
"divide": Parse both values as integers and perform division, catchingFormatExceptionfor parsing errors - For
"access": Create a list with the first value and access the index specified by the second value, catchingRangeErrorfor invalid indices - 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: 42If the inputs are "parse", "xyz", "unused", your program should output:
Operation: parse
Input: xyz
FormatException caught: Invalid number format
Please provide a valid integerIf the inputs are "divide", "10", "2", your program should output:
Operation: divide
Values: 10, 2
Division successful!
Result: 5If 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 numbersIf 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 0Your 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
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced List Manipulation
List Properties: first & lastList State: isEmpty & isNotEmpReversing a ListAdding to a List: insertList Removal: removeWhereFinding in a List: indexOfSorting a ListShuffling a ListRecap - List Organizer4Advanced Map Manipulation
Iterating Over a MapChecking for Keys and ValuesMap Properties: keys & valuesConditional Add: putIfAbsentRemoving Entries from a MapNested MapsRecap - Inventory Update2Functional List Operations
Transforming with 'map'Filtering with 'where'Using '.toList()'Checking Conditions with 'any'Conditions with 'every'Finding with 'firstWhere'Recap - Data Filtering5Project: Shopping Cart Calc
Project SetupAdding Items to the Cart3Sets
What is a Set?Creating a SetAdding and Removing from SetsChecking for Elements in a SetConverting a List to a SetSet UnionSet IntersectionSet DifferenceRecap - Unique Guest List6Basic Error Handling
What are Exceptions?The 'try-catch' BlockCatching Exceptions with 'on'The 'finally' BlockThrowing an ExceptionRecap - Safe Division