Dart14异常

1.try/on/catch块

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

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

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

2.使用on块

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

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

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

Cannot divide by zero

3.使用catch块

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

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

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

IntegerDivisionByZeroException

4.on…catch

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

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

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

IntegerDivisionByZeroException

5.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'); 
   } 
}

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

Cannot divide by zero 
Finally block executed

6.抛出异常

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

void test_age(int age) { 
   if(age<0) { 
      throw new FormatException(); 
   } 
}

main() { 
   try { 
      test_age(-2); 
   } 
   catch(e) { 
      print('Age cannot be negative'); 
   } 
}  

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

Age cannot be negative

7.内置异常

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

8.自定义异常

Dart中的每个异常类型都是内置类Exception的子类,Dart可以通过扩展现有异常来创建自定义异常。

class Custom_exception_Name implements Exception { 
   // can contain constructors, variables and methods 
}

以下示例显示如何定义和处理自定义异常。

class AmtException implements Exception { 
   String errMsg() => 'Amount should be greater than zero'; 
}  

void withdraw_amt(int amt) { 
   if (amt <= 0) { 
      throw new AmtException(); 
   } 
}

void main() { 
   try { 
      withdraw_amt(-1); 
   } 
   catch(e) { 
      print(e.errMsg()); 
   }  
   finally { 
      print('Ending requested operation.....'); 
   } 
}  

代码应该产生以下输出:

Amount should be greater than zero 
Ending requested operation....