How to create a custom exception and handle it in dart

FlutterDartExceptionTry Catch

Flutter Problem Overview


I have written this code to test how custom exceptions are working in the dart.

I'm not getting the desired output could someone explain to me how to handle it??

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

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

Flutter Solutions


Solution 1 - Flutter

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');
}

Solution 2 - Flutter

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");

Solution 3 - Flutter

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);
}

Solution 4 - Flutter

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...');
   }   
}    

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVickyonitView Question on Stackoverflow
Solution 1 - FlutterAlexandre ArdhuinView Answer on Stackoverflow
Solution 2 - FlutterSabrinaView Answer on Stackoverflow
Solution 3 - FlutterGuillem PucheView Answer on Stackoverflow
Solution 4 - FlutterSaboor KhanView Answer on Stackoverflow