How to create and handle custom exception in dart with example
This tutorial explains How to create a custom exception and handle or use it in Dart and Flutter.
Dart language provides different built exceptions and Errors. These are runtime failures and handles without graceful exit.
How to create Custom Exceptions in Dart
First, Custom Exception classes are created by implementing theException
interface.
class CloudConnectionException implements Exception
Next, Define the final variable that tells the exception description
final String? description;
To initialize this variable, Constructor is defined as given below
CloudConnectionException(this.description);
You can override the toString() method that returns the String version of a Custom Exception
@override
String toString() {
return 'CloudConnectionException: $description';
}
Here is a complete Custom Exception class code in Dart
class CloudConnectionException implements Exception {
final String? description;
CloudConnectionException(this.description);
@override
String toString() {
return 'CloudConnectionException: $description';
}
}
Custom Exceptions are defined with a string constructor.
Another simple example for creating Custom Exception without a constructor.
In the below
- Custom Exception by implementing Exception
- Create a Custom method that returns a string version using a lambda expression.
- Handle exceptions using try, catch.
Here is an example
class SimpleException implements Exception {
String description() => 'Simple Exception';
}
void main() {
try {
throw new SimpleException();
} on SimpleException catch (ex) {
print("custom exception cached");
print(ex.description());
}
}
So you have to catch or handle it.
How to Handle Custom Exceptions in Dart?
You can handle it similar to Inbuilt exceptions using try
, on
, and catch
keywords
Here is an example
class CloudConnectionException implements Exception {
final String? description;
CloudConnectionException(this.description);
@override
String toString() {
return 'CloudConnectionException: $description';
}
}
void main() {
try {
throw new CloudConnectionException('Cloud Connection Custom Exception');
} on CloudConnectionException catch (ex) {
print("custom exception cached");
print(ex.toString());
}
}
Conclusion
Dart provides Inbuilt Exceptions, as well as can create custom exceptions and handles them.