【Dart学习】-- Dart之异常处理

  概述:

    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<String> 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<String> 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之前执行
        }
      }
      复制代码

       

 

posted on   梁飞宇  阅读(2612)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
历史上的今天:
2017-06-14 Xcode编译警告Assigning to 'id<XXXDelegat> ——Nullable' from incompatible type 'XXXView *const_strong'
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示