DART语言中的异常处理示例
void main() {
var list = [1,2,3,4];
/IndexOutOfRangeException */
try{
print("Out of range execption................");
print(" ");
print(list[5]); //Try to access out of range variable.
}
catch(IndexOutOfRangeException ex){
print('The exception is: ${ex}');
}
/NoSuchMethodException */
try{
print("");
print("No such method exception................");
print("");
MethodExcep obj = new MethodExcep();
obj.IllegalMethod(); //you'r trying to access that method,which is not aviable.
}
catch(NoSuchMethodException ex){
print('The exception is: ${ex}');
}
/NullPointerException*/
try{
print("");
print("Null pointer exception................");
print("");
MethodExcep o = new MethodExcep();
o.a(null,2); //You want to perform operation on null value.
}
catch(NullPointerException ex){
print('The exception is: ${ex}');
}
finally{
print("All Exception all handled here");
}
}
class MethodExcep{
void Legal(){
print("I am a legal method");
}
a(int a, int b)
{
int c=a-b;
print(c);
}
}
DART语言的异常处理
DART旨在使用相同的机制来促进错误条件,基于Java和C++采用相同的机制。
例外(异常)是在执行程序期间发生的事件。
为了处理可能的错误条件,我们通常将程序的相关部分划分为三种不同类型的数量:
- 尝试块 try
Try块包含构成程序的正常操作的一部分的代码,但这可能会遇到一些严重的错误条件。 - 捕获块 catch
Catch块用于处理异常。 - Finally块
它位于Try块的末尾,并且不管是否发生了错误都会被执行。
其中一些常见的内置DART异常:
- IndexOutOfRangeException:
如果声明大小为4列表并想要访问它的第五个元素,那么它会给IndexOutofrangeException:5.
- nosuchmethodexception.
如果要访问代码中未给出的方法,则找到nosuchmethodexception:方法:"方法名称"发生异常。
- 空指针异常
发生NullPointerException,当我们向任何变量提供空值并且希望通过此变量的帮助执行某些操作。
日期:2020-04-11 23:04:01 来源:oir作者:oir
