Dart异常是运行时错误。程序获取时会提出。程序不会在程序内部运行时在编译时报告错误,如果Dart编译器发现不合适的东西。然后,报告运行时错误,程序的执行异常终止。此类型的错误称为例外。例如 - 给定的数字除以零,或者我们尝试从空列表中访问元素。
Dart支持以下类型的内置异常。
Sr. | Exceptions | Description |
---|---|---|
1. | DefferedLoadException | 当延迟的库无法加载时,将引发该错误。 |
2. | FromatException | 是抛出的异常 |
3. | IntegerDivisionByZeroException | 当数字除以零时将引发该错误。 |
4. | IOEException | 它是与输入输出相关的异常的基类。 |
5. | IsolateSpawnException | 当无法创建隔离时将抛出该错误。 |
6. | Timeout | 在等待异步结果时发生调度超时时,将引发此错误。 |
异常的主要目的是处理运行时错误并防止程序突然终止。 Dart中的每个例外都是预定义的类Exception的子类型
try块用于保存可能被抛出异常的代码块。 on块用于当我们需要指定例外时。 Catch块用于当处理程序需要异常对象时。
try { // 可能引发异常的代码 } on Exception1 { // 指定异常 } Catch Exception2 { //处理异常的代码 }
void main() { int x = 12; int y = 0; int res; try { res = x ~/ y; } on IntegerDivisionByZeroException { print('Cannot divide by zero'); } }
输出
Cannot divide by zero
void main() { int x = 12; int y = 0; int res; try { res = x ~/ y; } //它返回与发生的异常相关的内置异常 catch(E) { print(E); } }
输出
IntegerDivisionByZeroException
void main() { int x = 12; int y = 0; int res; try { res = x ~/ y; } on IntegerDivisionByZeroException catch(E) { print(E); } }
输出
IntegerDivisionByZeroException
无论是否发生异常,finally块始终执行。它在try/on/catch之后无条件执行。
链接:https://www.learnfk.comhttps://www.learnfk.com/dart-programming/dart-exceptions.html
来源:LearnFk无涯教程网
下面给出了finally块的语法。
try { //可能引发异常的代码 } on Exception1 { //异常处理代码或指定异常 } catch Exception2 { // 异常处理代码 } finally { //应始终执行的代码;不管是否有异常 }
让我们了解以下块的以下示例。
finally { void main() { int x = 12; int y = 0; int res; try { res = x ~/ y; } on IntegerDivisionByZeroException { print('Cannot divide by zero'); } print('Finally block always executed'); } }
输出
Cannot divide by zero Finally block executed
我们可以显式地或强制性地提出异常。应该处理显式引发的异常,以避免程序严重存在。语法在下面给出。
throw new Exception_name()
让我们了解以下示例。
main() { try { check_marks(-10); } catch(e) { print('The marks cannot be negative'); } } void check_marks(int marks) { if(marks<0) { throw new FormatException(); //对外抛出异常 } }
输出
The marks cannot be negative
如上所述,dart中的每个异常都是内置类Exception的子类型。 Dart通过扩展现有的异常类提供了创建自定义异常的灵活性。语法在下面给出。
class CusLearnfk_exception_Name implements Exception { //can contain constructors, variables and methods }
让我们了解以下代码。
class AmtException implements Exception { String expMsg() => 'Entered Amount should be greater than zero'; } void main() { try { withdraw_amt(-1); } catch(E) { print(E.expMsg()); } finally { print('Ending requested operation.....'); } } void withdraw_amt(int amt) { if (amt <= 0) { throw new AmtException(); } }
输出
Entered Amount should be greater than zero Ending requested operation.....
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)