dart_in_action/06_exception_handling.dart

66 lines
1.2 KiB
Dart

///
/// exception handling
///
main(List<String> args) {
// try ..on, 一般用于处理已知错误
try {
int result = 12 ~/ 0;
print("The result is $result");
} on IntegerDivisionByZeroException {
print('Cannot divide by Zero');
}
// try ..catch, 一般用于捕获未知错误
try {
int result = 12 ~/ 0;
print("The result is $result");
} catch (e) {
print("The exception thrown is $e");
}
// STACK TRAC
try {
int result = 12 ~/ 0;
print("The result is $result");
} catch (e, s) {
print("The exception thrown is $e");
print("STACK TRACE \n $s");
}
// finally
try {
int result = 12 ~/ 0;
print("The result is $result");
} catch (e) {
print("The exception thrown is $e");
} finally {
print("This is FINALLY Clause and is always executed.");
}
// try ..finally
try {
int result = 12 ~/ 1;
print("The result is $result");
} finally {
print("This is FINALLY Clause and is always executed.");
}
// Custom Exception
try {
throwFunc();
} catch (e) {
print(e);
}
}
class CustomException implements Exception {
@override
String toString() {
return "This is Custom Exception.";
}
}
throwFunc() {
throw CustomException();
}