Dart/Flutter: exception handling
The exceptions are triggered every time an error happens during the software execution. In case exceptions are not handled, the software will abort, and the program execution will ends. To make the software with capability to handle its errors and give to the users a proper feedback and possibility to correct some input or try again, the exceptions can be handled.
To perform
exception handling using Dart, which is the programming language adopted by
Flutter technology, you may use the try / on statement was we have in the example
below:
int x = 12;
int y = 0;
int res;
print("1) try / on statement");
try {
res = x ~/
y; // ~/ => truncating division
operator, always returns a int value.
}
on IntegerDivisionByZeroException {
print('Exception::
Cannot divide by zero');
}
Another possibility is to have the same structure but with the addition of the catch keyword. It makes possible to have access to the exception object and to read data from that. This kind of resource could be very useful for logging purposes to assist to find the root cause of an error.
print("2)
try / on / catch statement");
try {
res = x ~/
y;
}
on IntegerDivisionByZeroException catch(e)
{
print(e);
print('Exception::
Cannot divide by zero');
}
And beyond the possibilities to handle the exception if “on” and to have access to the exception object with “catch”, we can use the finally structure. The finally is quiet useful when we have a block of code that has to be executed after instructions that are protected within the try statement are concluded. The block of code within finally is executed always, independently if there is an exception triggered within the try statement or not. You can see an example of this structure here:
You can
download the source code from here:
try {
res = x ~/
y;
}
on IntegerDivisionByZeroException catch(e)
{
print(e);
print('Exception::
Cannot divide by zero');
}
finally{
print("Finally
block: always execute => no matter if there is execption or not.");
}
https://github.com/rafaelqg/code/blob/main/exception_handling.dart
You may see
a demonstration of this code in a video class here:
https://www.youtube.com/watch?v=I8zhwiu9CF8
Comments
Post a Comment