How to use custom exceptions in dart

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) {


  • 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

You might also like: