【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之前執行
        }
      }

       

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM