Exceptions
An exception is a signal that a condition has occurred that can’t be easily handled using the normal flow-of-control of a Dart program. Exceptions are often defined as being “errors” but this is not always the case. All errors in Dart are dealt with using exceptions, but not all exceptions are errors.
Every exception in Dart is a subtype of the pre-defined class Exception. Exceptions must be handled to prevent the application from terminating abruptly.
Built-in Dart exceptions include :
Exception | Description |
---|---|
DeferredLoadException | Thrown when a deferred library fails to load. |
FormatException | Exception thrown when a string or some other data does not have an expected format and cannot be parsed or processed. |
IntegerDivisionByZeroException | Thrown when a number is divided by zero. |
IOException | Base class for all Inupt-Output related exceptions. |
IsolateSpawnException | Thrown when an isolate cannot be created. |
Timeout | Thrown when a scheduled timeout happens while waiting for an async result. |
Others | .... |
Examples:
void main() {
int x = 3, y = 0;
print(x ~/ y);
}
IntegerDivisionByZeroException
void main() {
int x = 15, y = 0;
double w = x / y;
print(w);
w -= 500 / 0;
print(w);
}
NaN
The key here is that n / 0 is not integer division.
Dart automatically performs double division and the double type has the double.infinity constant. This means that print(n / 0) will yield Infinity.
Furthermore, double.infinity is actually defined as 1.0 / 0.0.
If you use integer division instead (~/), you will receive an IntegerDivisionByZeroException:
void main() {
List li = [0, 1, 2];
print(li[6]);
}
RangeError (index): Invalid value: Not in inclusive range 0..2: 6