Exceptions in Dart provide a powerful mechanism for managing errors and unexpected situations in your code. They allow you to gracefully handle runtime errors, maintaining program stability and improving user experience.
An exception is an object representing an error or unexpected event that occurs during program execution. When an exception is thrown, it disrupts the normal flow of the program. Dart's exception handling system allows you to catch and respond to these errors.
Dart provides several built-in exception types:
Exception
: A generic exception classFormatException
: Thrown when a string or some other data does not have an expected formatIOException
: Related to input/output operationsStateError
: Indicates that an object is in an invalid stateYou can throw exceptions using the throw
keyword. Here's a simple example:
void checkAge(int age) {
if (age < 0) {
throw ArgumentError('Age cannot be negative');
}
}
To handle exceptions, use a try-catch block. This allows you to attempt potentially error-prone code and handle any exceptions that occur:
try {
checkAge(-5);
} catch (e) {
print('An error occurred: $e');
}
The finally
clause executes code regardless of whether an exception was thrown or caught. It's useful for cleanup operations:
try {
// Some risky operation
} catch (e) {
print('Error: $e');
} finally {
print('This always runs');
}
You can create custom exceptions by extending the Exception
class:
class InsufficientFundsException implements Exception {
String errMsg() => 'Insufficient funds';
}
void withdraw(double amount) {
if (amount > balance) {
throw InsufficientFundsException();
}
// Proceed with withdrawal
}
Exception
or Error
directly; be specificrethrow
to propagate exceptions you can't fully handleEffective exception handling is crucial for building robust Dart applications. By understanding and properly implementing exception handling techniques, you can create more reliable and user-friendly software. Remember to use async and await when dealing with asynchronous operations, as they have their own set of exception handling considerations.