Home > Mobile >  throw Exception('oops!') vs throw 'oops!'
throw Exception('oops!') vs throw 'oops!'

Time:09-29

I notices some code that made me think the Exception function call was optional? E.g., do these two lines perform the same function?

throw Exception('oops!');
throw 'oops!'

CodePudding user response:

No. The former, throw Exception('oops!');, creates a new Exception object using the Exception constructor, then throws that object. It can be caught by try { ... } on Exception catch (e) { ... }.

The latter, throw 'oops!'; throws the string object. It can be caught by try { ... } on String catch (e) { ... }.

Generally, you shouldn't be doing either.

If someone made an error, something that would have been nice to catch at compile-time and reject the program, but which happens to not be that easy to detect, throw an Error (preferably some suitable subclass of Error). Errors are not intended to be caught, but to make the program fail visibly. Some frameworks do catch errors and log them instead. They're typically able to restart the code which failed and carry on, without needing to understand why.

If your code hit some exceptional situation which the caller should be made aware of (and which prevents just continuing), throw a specific subclass of Exception, one which contains the information the caller needs to programmatically handle that situation. Document that the code throws this particular exception. It's really a different kind of return value more than it's an error report. Exceptions are intended to be caught and handled. Not handling an exception is, itself, an error (which is why it's OK for an uncaught exception to also make the program fail visibly).

If you're debugging, by all means throw "WAT!"; all you want. Just remove it before you release the code.

  •  Tags:  
  • dart
  • Related