Do you need to create a custom exception class in Dart? Find out in this tutorial.
If an unwanted condition occurs, you can throw an Exception that will be handled later. Dart already has the Exception class, but sometimes it's necessary to use custom exception class. With custom exception class, it makes us easier to use different handling for certain errors. In addition, by creating custom exceptions specific to business logic, it helps the users and the developers to understand the problem.
In Dart, the custom exception class must implement Exception
class. An exception usually has an error message and therefore the custom exception class should be able to return an error message. You can create a method with any name for returning the error message, but this tutorial uses toString()
which is the same name used in Dart's Exception class.
Usually the error message is set when the exception instance is created by calling the constructor. Therefore, based on need, the constructor may also need to have a parameter for setting the error message. This example uses a constructor with one optional parameter which is the error message, but a default value is also provided in case the caller doesn't pass error message.
Below is the full code example which includes the custom Exception class, the usage, as well as the error handling.
class ValueException implements Exception {
String _message;
ValueException([String message = 'Invalid value']) {
this._message = message;
}
@override
String toString() {
return _message;
}
}
void validateValue(int value) {
if (value == null) {
throw new ValueException();
} else if (value <= 0) {
throw new ValueException("Value must be greater than 0");
} else if (value > 100) {
throw new ValueException("Value must not be greater than 100");
}
}
void main(List<String> arguments) {
List<int> values = [-1, 50, 200];
values.forEach((value) {
try {
validateValue(value);
} catch (e) {
print('Error: ${e.toString()}');
}
});
}