Dart2基础(七) - 异常处理

 

目录

抛出异常

捕获异常

finally


Dart2的异常与Java是非常类似的。Dart2的异常是Exception或者Error(包括它们的子类)的类型,甚至可以是非Exception或者Error类,也可以抛出,但是不建议这么使用。

Exception主要是程序本身可以处理的异常,比如:IOException。我们处理的异常也是以这种异常为主。

Error是程序无法处理的错误,表示运行应用程序中较严重问题。大多数错误与代码编写者执行的操作无关,而表示代码运行时 DartVM出现的问题。比如:内存溢出(OutOfMemoryError)等等。

与Java不同的是,Dart2是不检测异常是否声明的,也就是说方法或者函数不需要声明要抛出哪些异常。

  • 抛出异常

使用throw抛出异常,异常可以是Excetpion或者Error类型的,也可以是其他类型的,但是不建议这么用。另外,throw语句在Dart2中也是一个表达式,因此可以是=>。

// 非Exception或者Error类型是可以抛出的,但是不建议这么用
testException(){
    throw "this is exception";
}
testException2(){
    throw Exception("this is exception");
}

// 也可以用 =>
void testException3() => throw Exception("test exception");
  • 捕获异常

使用on可以捕获到某一类的异常,但是获取不到异常对象; catch可以捕获到异常对象。这个两个关键字可以组合使用。

rethrow可以重新抛出捕获的异常。

testException(){
  throw FormatException("this is exception");
}

main(List args) {
  try{
    testException();
  } on FormatException catch(e){ // 如果匹配不到FormatException,则会继续匹配
    print("catch format exception");
    print(e);
    rethrow; // 重新抛出异常
  } on Exception{ // 匹配不到Exception,会继续匹配 
   print("catch exception") ;
  }catch(e, r){ // 匹配所以类型的异常. e是异常对象,r是StackTrace对象,异常的堆栈信息
    print(e);
  }
}
  • finally

finally内部的语句,无论是否有异常,都会执行。

testException(){
  throw FormatException("this is exception");
}

main(List args) {
  try{
    testException();
  } on FormatException catch(e){
    print("catch format exception");
    print(e);
    rethrow;
  } on Exception{
   print("catch exception") ;
  }catch(e, r){ 
    print(e);
  }finally{
    print("this is finally"); // 在rethrow之前执行
  }
}

 

你可能感兴趣的:(dart2,教程)