2

According to the following resources: https://api.dart.dev/stable/2.4.0/dart-core/Exception-class.html https://api.dart.dev/stable/2.4.0/dart-core/Error-class.html https://groups.google.com/a/dartlang.org/g/misc/c/lx9CXiV3o30/m/s5l_PwpHUGAJ?pli=1 https://groups.google.com/a/dartlang.org/g/misc/c/lx9CXiV3o30/m/s5l_PwpHUGAJ?pli=1

It's absolutely clear to me what the difference is, between an Exception and an Error:

  • An Error should be thrown, when the programmer made a mistake and he should fix that mistake. Example: Making sure the parameters of a method are not null.
  • An Exception should be thrown, when it's intended to catch the exception and handle it. Example: A database call is executed, but there is no internet connection available

I also understand, how assertions work. All assert statements are removed, in production code. A failing assert statement throws an AssertionError, which makes sense because a failing assert is always the programmer's fault.

But now the following question arises: (Question 1) When should I throw an Error (or a subclass of Error) and when should I use an assert statement? The purpose of both concepts is to alert the programmer that he made a mistake.

Given the following method (Please assume a much more complicated use case):

void test(Test test){
   // assert or throw ArgumentError here?
   test.abc();
}

I can make sure that the pre-conditions for the method are met, using assert(test != null), or by if(test == null) throw ArgumentError.notNull("test");. In both cases, the program will fail in production, but when using assert I get a NoSuchMethodError because the assert is removed and when throwing an ArgumentError it's more detailed because the ArgumentError directly points to the underlying issue (the method was called with null as a parameter).

As shown above, the program fails in both cases in production. But throwing an Error gives many more details about the cause of the issue.

(Question 2) Why does Flutter use assert everywhere, instead of throwing Errors?

Niklas Raab
  • 1,576
  • 1
  • 16
  • 32
  • `assert` is more convenient for checking parameters in constructors as it can be used in initializer lists. However, it is only valid for debug builds (it gets compiled out entirely in release builds), so if you are doing manual checking of parameters within method bodies, it's better to throw errors. – Abion47 Oct 20 '20 at 18:50
  • 2
    I recommend reading this thread https://stackoverflow.com/questions/57833399/whats-the-recommended-way-in-dart-asserts-or-throw-errors – Karol Lisiewicz Oct 20 '20 at 18:53

0 Answers0