Gestire le eccezioni in Dart
Dart ha un modo un pò diverso di gestire le eccezioni, in quanto è possibile usare sia on che catch:
- on -> viene deciso quale eccezione controllare, e viene stampato un messaggio custom
- catch -> viene intercettata qualsiasi eccezione, ed è possibile visualizzare quale viene intercettata
Qua sotto vi ho postato 4 esempi:
- usando on
- usando catch
- usando un mix dei due
- come il primo, ma con finally
Ecco qua:
main() {
int x = 12;
int y = 0;
int res;
// ESEMPIO UNO
try {
res = x ~/ y;
} on IntegerDivisionByZeroException {
print('Non è possibile dividere per zero');
}
// ESEMPIO DUE
try {
res = x ~/ y;
} catch (e) {
print(e);
}
// ESEMPIO TRE
try {
res = x ~/ y;
} on IntegerDivisionByZeroException catch (e) {
print(e);
}
// ESEMPIO QUATTRO
try {
res = x ~/ y;
} on IntegerDivisionByZeroException {
print('Non è possibile dividere per zero');
} finally {
print('FINE');
}
}
Enjoy!
dart eccezioni try catch
Commentami!