Dart语言教程:异常try/on/catch块

2023年 7月 13日 50.7k 0

异常(或异常事件)是在执行程序期间出现的问题。发生异常时,程序的正常流程中断,程序/应用程序异常终止。

Dart内置异常如下 -

编号 异常 描述
1 DeferredLoadException 延迟库无法加载时抛出。
2 FormatException 当字符串或某些其他数据没有预期格式且无法解析或处理时抛出异常。
3 IntegerDivisionByZeroException 当数字除以零时抛出。
4 IOException 所有与输入输出相关的异常的基类。
5 IsolateSpawnException 无法创建隔离时抛出。
6 Timeout 在等待异步结果时发生计划超时时抛出。

Dart中的每个异常都是预定义类Exception的子类,必须处理异常以防止应用程序突然终止。

try/on/catch块

try块嵌入可能导致异常的代码。需要指定异常类型时使用on块。当处理程序需要异常对象时使用catch块。

try块必须紧跟一个on/catch块或一个finally块(或两者之一)。当try块中发生异常时,控制将转移到catch

处理异常的语法如下所示 -

try { 
   // code that might throw an exception 
}  
on Exception1 { 
   // code for handling exception 
}  
catch Exception2 { 
   // code for handling exception 
}

Dart

以下是要记住的一些要点 -

  • 代码段可以有多个on/catch块来处理多个异常。
  • on块和catch块是相互包含的,即try块可以与on块和catch块相关联。

示例:使用on块

以下程序分别用变量xy表示的两个数字。代码抛出异常,因为它尝试除以0on块包含处理此异常的代码。

main() { 
   int x = 12; 
   int y = 0; 
   int res;  

   try {
      res = x ~/ y; 
   } 
   on IntegerDivisionByZeroException { 
      print('Cannot divide by zero'); 
   } 
}

Dart

执行上面示例代码,得到以下结果 -

Cannot divide by zero

Shell

示例:使用catch块

在以下示例中,使用了与上面相同的代码。唯一的区别是在catch块(而不是on块)包含处理异常的代码。catch的参数包含在运行时抛出的异常对象。

main() { 
   int x = 12; 
   int y = 0; 
   int res;  

   try {  
      res = x ~/ y; 
   }  
   catch(e) { 
      print(e); 
   } 
}

Dart

执行上面示例代码,得到以下结果 -

IntegerDivisionByZeroException

Shell

示例:on…catch

以下示例显示如何使用on...catch块。

main() { 
   int x = 12; 
   int y = 0; 
   int res;  

   try { 
      res = x ~/ y; 
   }  
   on IntegerDivisionByZeroException catch(e) { 
      print(e); 
   } 
}

Dart

执行上面示例代码,得到以下结果 -

IntegerDivisionByZeroException

Shell

finally块

finally块包括应该执行的代码,而不管异常的发生。try/on/catch之后无条件执行可选的finally块。

使用finally块的语法如下 -

try { 
   // code that might throw an exception 
}  
on Exception1 { 
   // exception handling code 
}  
catch Exception2 { 
   //  exception handling 
}  
finally { 
   // code that should always execute; irrespective of the exception 
}

Dart

以下示例说明了finally块的使用。

main() { 
   int x = 12; 
   int y = 0; 
   int res;  

   try { 
      res = x ~/ y; 
   } 
   on IntegerDivisionByZeroException { 
      print('Cannot divide by zero'); 
   } 
   finally { 
      print('Finally block executed'); 
   } 
}

Dart

执行上面示例代码,得到以下结果:

Cannot divide by zero 
Finally block executed

Shell

抛出异常

throw关键字用于显式引发异常。应该处理引发的异常,以防止程序突然退出。

引发异常的语法是 -

throw new Exception_name()

Dart

示例

以下示例显示如何使用throw关键字抛出异常 -

main() {
try {
test_age(-2);
}
catch(e) {
print('Age cannot be negative');
}
}
void test_age(int age) {
if(age 'Amount should be greater than zero';
}
void main() {
try {
withdraw_amt(-1);
}
catch(e) {
print(e.errMsg());
}
finally {
print('Ending requested operation.....');
}
}
void withdraw_amt(int amt) {
if (amt

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论