How to create a custom exception and handle it in dart

Try this Simple Custom Exception Example for Beginners

class WithdrawException implements Exception{
  String wdExpMsg()=> 'Oops! something went wrong';
}

void main() {   
   try {   
      withdrawAmt(400);
   }   
  on WithdrawException{
    WithdrawException we=WithdrawException();
    print(we.wdExpMsg());
  }
  finally{
    print('Withdraw Amount<500 is not allowed');
  }
}

void withdrawAmt(int amt) {   
   if (amt <= 499) {   
      throw WithdrawException();   
   }else{
     print('Collect Your Amount=$amt from ATM Machine...');
   }   
}    

You can look at the Exception part of A Tour of the Dart Language.

The following code works as expected (custom exception has been obtained is displayed in console) :

class CustomException implements Exception {
  String cause;
  CustomException(this.cause);
}

void main() {
  try {
    throwException();
  } on CustomException {
    print("custom exception has been obtained");
  }
}

throwException() {
  throw new CustomException('This is my first custom exception');
}

You don't need an Exception class if you don't care about the type of Exception. Simply fire an exception like this:

throw ("This is my first general exception");

You can also create an abstract exception.

Inspiration taken from TimeoutException of async package (read the code on Dart API and Dart SDK).

abstract class IMoviesRepoException implements Exception {
  const IMoviesRepoException([this.message]);

  final String? message;

  @override
  String toString() {
    String result = 'IMoviesRepoExceptionl';
    if (message is String) return '$result: $message';
    return result;
  }
}

class TmdbMoviesRepoException extends IMoviesRepoException {
  const TmdbMoviesRepoException([String? message]) : super(message);
}