96

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');
}
Vickyonit
  • 1,077
  • 1
  • 7
  • 8
  • Did you defined a `customException` class ? If yes, could you add its code to your question. – Alexandre Ardhuin Nov 27 '12 at 08:28
  • 1
    class customException implements Exception { String _message = ""; customException([this._message]); String toString() => "LatLngException: message=${_message}"; }i solve this using this piece of code defined @AlexandreArdhuin is correct – Vickyonit Nov 27 '12 at 08:37

4 Answers4

168

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');
}
Carrie Kendall
  • 11,124
  • 5
  • 61
  • 81
Alexandre Ardhuin
  • 71,959
  • 15
  • 151
  • 132
  • 4
    i want my exception to be inherited from the Exception class. – Vickyonit Nov 27 '12 at 08:40
  • 3
    FYI : *Dart programs can throw any non-null object—not just Exception and Error objects—as an exception* – Alexandre Ardhuin Nov 27 '12 at 08:45
  • 8
    @Vickyonit do not inherit from the Exception class, implement it instead. Also, you may want to consider adding a code to the class as well. – Kai Sellgren Nov 27 '12 at 12:08
  • 2
    Wouldn't you want the Exception's members to be marked as `final`? – Oleg Silkin Nov 12 '18 at 01:04
  • 1
    @OlegSilkin Yes, always make things final unless mutations are a requirement. Exceptions should never mutate. – DarkNeuron May 24 '19 at 10:32
  • @KaiSellgren should we implement over extend because `Exception` is abstract? What about extending from concrete implementations like [`SocketException`](https://github.com/dart-lang/sdk/blob/04b7b090eb5dd714654faa80843c1feadc1ccede/sdk/lib/io/socket.dart#L981)? – micimize Aug 25 '19 at 16:45
  • Interesting. new is opitonal in my version of dart, but its helpful to understand its calling the constructor in your example. – netskink Sep 18 '20 at 01:34
  • to get the custom exception instance: `on CustomException catch(e) {...` – Sang Jul 17 '22 at 07:19
54

If you don't need to be specific about the problem, you can throw a general issue like this:

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

But it's better to use specific errors when possible. They tell you more about what went wrong so you can figure out how to fix it.

Sabrina
  • 2,531
  • 1
  • 32
  • 30
  • 2
    With [reference](https://dart.dev/guides/language/language-tour#exceptions) to "Dart programs can throw any non-null object—not just *Exception* and Error objects—as an **exception**." (emphasis mine), I've made an edit to your post because the actual type of the object thrown here is *String*, which you can verify by the following code snippet: `void main() { try { throw ("Your description is a String");} catch (e) { print(e.runtimeType); } }` – Ardent Coder Dec 19 '20 at 08:24
3

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);
}
Guillem Puche
  • 1,199
  • 13
  • 16
1

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...');
   }   
}    
Seiji Hirao
  • 310
  • 2
  • 16