Dart Custom Exception Handling Class with Example
How to use custom exceptions in dart:
Dart already provides Exception class and we can use this to throw an exception. But this is a predefined class and we can’t customize it as per our need. For example, if we need to add more information to the exception before it is thrown, we can’t do that in the system Exception class.
In such scenarios, custom exception comes to the picture. This is simply a class that implements Exception class. So, if we create an object for custom exception, we can use it like other exceptions i.e. we can throw it. In the catch or on block, we can get data from the object.
Custom exception class:
To create a custom exception, we need to :
- implement it from Exception class.
- We can also override the methods of Exception class like toString method.
- We can add other extra variables in this class.
Dart program that uses custom exception:
Let’s take a look at the below program:
class PasswordException implements Exception {
String msg;
int errorCode;
PasswordException(String msg, int error) {
this.msg = msg;
this.errorCode = error;
}
String toString() {
return "Message : $msg, Error code $errorCode";
}
}
void main() {
var password = "abcd";
try {
if (password.length < 5) {
throw PasswordException("Password length should be more than 5", 333);
}
} on PasswordException catch (e) {
print(e.toString());
}
}
Here,
- PasswordException is a custom exception class.
- We can initialize the class with a string message and one integer error value. The toString method prints out the message and the error value.
- In main, we are throwing this exception and printing the result by calling toString.
It prints the below output:
Message : Password length should be more than 5, Error code 333
Dart Custom Exception Handling Class
Now we have created a custom Class named GradeException and it implements the Exception interface. The GradeException class has only one method that returns a string message that marks cannot be negative.
Let’s write the main function with a simple checkMarks function which throws an exception of type GradeException. Run the code.
Here is the result. As the marks are -ve values and exception is not handled. An expected Unhandled exception is thrown.
It is time to handle this exception and return a message of our own choice. Again simply use a try-catch block to handle the exception or try-on block. Here is the code with try-catch block.
Run the code and BOOM check the console. The exception is handled in a pretty much better way.
Write a MarksMoreThanTotal function with proper exception handling and share your experience.
We hope you have enjoyed learning this cool Dart Custom Exception Handling Class tutorial. Please do let us know.
Comments
Post a Comment