Throwing Error
- Throwing an Exception
- Custom Exceptions
To explicitly raise an exception, we can use the throw keyword. A raised exception should be handled to prevent the program from exiting abruptly.
void main() {
String ticketNumber = "34253423";
try {
if (ticketNumber.length != 12) {
throw new FormatException();
}
} catch (e) {
print('the ticket number is composed of 12 digits');
}
}
You often can achieve that by using standard exceptions with good messages. The Dart Exception class describes the kind of event, and the message provides detailed information about it. You can take this concept one step further by using a custom exception.
Custom exceptions provide you the flexibility to add attributes and methods that are not part of a standard Java exception. These can store additional information, like an application-specific error code, or provide utility methods that can be used to handle or present the exception to a user.
class startWith1 implements Exception {
String erroMessage() => "The ticket number must start with 1.";
}
void main() {
String ticketNumber = "342531231234";
try {
if (ticketNumber[0] != 1) {
throw new startWith1();
}
} catch (e) {
print(e.erroMessage());
}
}