Dart Exceptions
Dart Exceptions
An exception is a problem that happens while a program is running.
For example, the user types "abc" where the program expects a number.
When an exception happens and nothing handles it, the program stops and prints an error message:
Example
void main() {
print('Start');
var age = int.parse('abc');
print(age);
print('End');
}
Try it Yourself »
Result:
Start
Unhandled exception:
FormatException: Invalid radix-10 number (at character 1)
abc
^
The program printed "Start", but it never reached "End".
The error message tells you the type of the exception (FormatException) and the reason.
On your own computer, Dart also prints a stack trace, which shows where the problem happened.
try and catch
To handle an exception, put the code that can fail in a try block.
If an exception happens, Dart jumps to the catch block, and the program continues after it:
Example
void main() {
print('Start');
try {
var age = int.parse('abc');
print(age);
} catch (e) {
print('That is not a number');
print(e);
}
print('End');
}
Try it Yourself »
Result:
Start
That is not a number
FormatException: Invalid radix-10 number (at character 1)
abc
^
End
The variable e holds the exception object, so you can print it or read its message.
The rest of the try block is skipped, so print(age) never runs.
Catch a Specific Type with on
A plain catch catches every kind of exception.
Often, you only want to handle one kind.
Use on followed by a type to catch only exceptions of that type:
Example
void main() {
try {
var price = double.parse('ten');
print(price);
} on FormatException {
print('Please enter a valid price');
}
}
Try it Yourself »
Result:
Please enter a valid price
You can have several on blocks, one for each type.
Add catch (e) after the type when you also need the exception object:
Example
int divide(int a, int b) {
if (b == 0) {
throw ArgumentError('b cannot be zero');
}
return a ~/ b;
}
void main() {
for (var input in ['20', 'twenty', '0']) {
try {
var number = int.parse(input);
print(divide(100, number));
} on FormatException catch (e) {
print('Not a number: ${e.source}');
} on ArgumentError catch (e) {
print('Bad argument: ${e.message}');
}
}
}
Try it Yourself »
Result:
5
Not a number: twenty
Bad argument: b cannot be zero
Dart checks the on blocks from top to bottom, and uses the first one that matches.
finally
The finally block always runs at the end, whether there was an exception or not.
It is used for cleanup work, like closing a file or a connection:
Example
void readScore(String text) {
try {
var score = int.parse(text);
print('Score: $score');
} on FormatException {
print('Invalid score: $text');
} finally {
print('Done reading');
}
}
void main() {
readScore('85');
readScore('high');
}
Try it Yourself »
Result:
Score: 85
Done reading
Invalid score: high
Done reading
throw and rethrow
You can throw an exception yourself with the throw keyword.
This is useful when a function gets a value it cannot work with:
Example
void setAge(int age) {
if (age < 0) {
throw Exception('Age cannot be negative');
}
print('Age set to $age');
}
void main() {
try {
setAge(25);
setAge(-5);
} catch (e) {
print(e);
}
}
Try it Yourself »
Result:
Age set to 25
Exception: Age cannot be negative
Sometimes you want to do something with an exception, like writing it to a log, and then let it continue up to the code that called you.
Use rethrow inside a catch block to throw the same exception again:
Example
int parseQuantity(String text) {
try {
return int.parse(text);
} on FormatException {
print('Log: could not read "$text"');
rethrow;
}
}
void main() {
try {
parseQuantity('five');
} on FormatException catch (e) {
print('main() caught: ${e.message}');
}
}
Try it Yourself »
Result:
Log: could not read "five"
main() caught: Invalid radix-10 number
Exception vs Error
Dart has two main kinds of problems:
- An
Exceptionis a problem that you expect can happen, like bad user input or a missing file. Your program should catch and handle it. - An
Erroris a bug in the program, like using a list index that does not exist. You should fix the code, not catch the error.
For example, FormatException is an Exception, and RangeError is an Error:
Example
void main() {
var fruits = ['Apple', 'Banana'];
try {
print(fruits[5]);
} catch (e) {
print(e);
print(e is Error);
print(e is Exception);
}
}
Try it Yourself »
Result:
RangeError (length): Invalid value: Not in inclusive range 0..1: 5
true
false
The right fix here is to check the length of the list before you read from it.
The null safety and type checks in Dart also help you find many errors before the program runs.
The Stack Trace
A stack trace is a list of the function calls that led to the exception.
It shows you where the problem started, which is very helpful when you look for a bug.
Add a second variable to catch to get the stack trace:
Example
int parseAge(String text) {
return int.parse(text);
}
void main() {
try {
parseAge('old');
} catch (e, stackTrace) {
print('Error: $e');
print('Stack trace:');
print(stackTrace);
}
}
Try it Yourself »
Result:
Error: FormatException: Invalid radix-10 number (at character 1)
old
^
Stack trace:
#0 int._handleFormatError (dart:core-patch/integers_patch.dart:150:5)
#1 int._parseRadix (dart:core-patch/integers_patch.dart:179:14)
#2 int._parse (dart:core-patch/integers_patch.dart:121:12)
#3 int.parse (dart:core-patch/integers_patch.dart:81:12)
#4 parseAge (main.dart:2:14)
#5 main (main.dart:7:5)
#6 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:313:19)
#7 _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
Read the stack trace from the top: the first lines are inside Dart's own code, and then you find your own functions, parseAge and main, with their line numbers.
Tip: In the next chapter, you will learn how to create your own custom exceptions.