Error handling
- Dart course
- Beginner
- Lesson 22/116
- 6 min
Safely catch invalid inputs with try/catch.
Catching errors with try/catch
When an error occurs the program crashes. With try/catch you catch the error and keep the program running.
Structure: try { ... risky code ... } catch (e) { ... on error ... }. e carries the caught error; print('Error: $e') shows the detail.
In this lesson we will add a try block inside main with throw Exception('Invalid input'). The catch block catches the error and prints a message.
Practice Add try/catch
Add a try block inside main. Write throw Exception('Invalid input') inside it. Then catch it with catch (e) { print('Error: $e'); }.
Starter code
void main() {
print('Calculator ready');
print(add(3, 4));
print(subtract(10, 3));
print(multiply(5, 6));
print(divide(10, 4));
// Add a try/catch block
}
int add(int a, int b) => a + b;
int subtract(int a, int b) => a - b;
int multiply(int a, int b) => a * b;
double divide(int a, int b) => a / b;Sample solution
void main() {
print('Calculator ready');
print(add(3, 4));
print(subtract(10, 3));
print(multiply(5, 6));
print(divide(10, 4));
try {
throw Exception('Invalid input');
} catch (e) {
print('Error: $e');
}
}
int add(int a, int b) => a + b;
int subtract(int a, int b) => a - b;
int multiply(int a, int b) => a * b;
double divide(int a, int b) => a / b;Expected output
Calculator ready 7 7 30 2.5 Error: Exception: Invalid input
throw and finally
With throw you deliberately raise an error. For example throw Exception('Divide by zero');. This stops the program flow and jumps to the matching catch.
The finally block always runs, error or not: try { ... } catch (e) { ... } finally { ... }. It is used for cleanup.
In the calculator you can use throw for invalid cases like divide by zero. We will see finally later for things like closing files.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Error catching
try { throw Exception('Error'); } ____ (e) { print('Caught: $e'); }
try { throw Exception('Error'); } catch (e) { print('Caught: $e'); }
Explanation: The catch block catches the error.
2 When does the catch block run?
- When an error occurs Correct answer
- Before try
- Always
- Never
Explanation: catch runs when an error is thrown inside try.
3 Error handling concepts
| Term | Meaning |
|---|---|
try |
Try block |
catch |
Catch |
throw |
Throw |
finally |
Finally always |