Advanced Techniques and Reflection
There is always some confusion on deciding when to use each kind of fault, but you
will be given several general rules to make your life a bit easier. All your decisions
will be based on the simple principle of recoverability. If your code generates a fault
that can reasonably be recovered from, use exceptions. Conversely, if the code
generates a fault that cannot be recovered from, or where continuing the execution
would do more harm, use errors.
Let's take a look at each of them in detail.
Errors
An error occurs if your code has programming errors that should be fixed by the
programmer. Let's take a look at the following main function:
main() {
// Fixed length list List
list = new List(5);
// Fill list with values
for (int i = 0; i < 10; i++)
{ list[i] = i;
}
print('Result is ${list}');
}
We created an instance of the List class with a fixed length and then tried to fill it
with values in a loop with more items than the fixed size of the List class. Executing
the preceding code generates RangeError, as shown in the following screenshot:

This error occurred because we performed a precondition violation in our code
when we tried to insert a value in the list at an index outside the valid range.
Mostly, these types of failures occur when the contract between the code and the
calling API is broken. In our case, RangeError indicates that the precondition was
violated. There are a whole bunch of errors in the Dart SDK such as CastError,
RangeError, NoSuchMethodError, UnsupportedError, OutOfMemoryError, and
StackOverflowError. Also, there are many others that you will find in the errors.
dart file as a part of the dart.core library. All error classes inherit from the Error
class and can return stack trace information to help find the bug quickly. In the
preceding example, the error happened in line 6 of the main method in the
range_error.dart file.
[ 10 ]