C++ 和 Java 中異常處理的比較


異常處理功能現在幾乎存在於任何面向物件的語言中。在 C++ 和 Java 中,我們也可以獲得這種功能。C++ 中的異常處理和 Java 中的異常處理之間存在一些相似之處,例如,在這兩種語言中,我們都必須使用 try-catch 塊。儘管也存在一些差異。這些差異如下所示:

在 C++ 中,我們可以丟擲任何型別的作為異常的資料。任何型別的資料意味著基本資料型別和指標。在 Java 中,我們只能丟擲可丟擲物件。任何可丟擲類的子類也可以丟擲。

示例

 線上演示

#include <iostream>
using namespace std;
int main() {
   int x = -5;
   try { //protected code
      if( x < 0 ) {
         throw x;
      }
   }
   catch (int x ) {
      cout << "Exception Caught: thrown value is " << x << endl;
   }
}

輸出

Exception Caught: thrown value is -5

在 C++ 中,有一個名為 catch all 的選項可以捕獲任何型別的異常。語法如下:

try {
   //protected code
} catch(…) {
   //catch any type of exceptions
}

示例

 線上演示

#include <iostream>
using namespace std;
int main() {
   int x = -5;
   char y = 'A';
   try { //protected code
      if( x < 0 ) {
         throw x;
      }
      if(y == 'A') {
         throw y;
      }
   }
   catch (...) {
      cout << "Exception Caught" << endl;
   }
}

輸出

Exception Caught

在 Java 中,如果我們想捕獲任何型別的異常,則必須使用 Exception 類。它是 Java 中任何異常或某些使用者定義異常的超類。語法如下:

try {
   //protected code
} catch(Exception e) {
   //catch any type of exceptions
}

C++ 沒有 finally 塊。但在 Java 中,有一個特殊的塊稱為 finally。如果我們在 finally 塊中編寫一些程式碼,它將始終被執行。如果 try 塊在沒有錯誤的情況下執行,或者發生異常,finally 塊將始終被執行。

Java 線上演示

示例

 線上演示

public class HelloWorld {
   public static void main(String []args) {
      try {
         int data = 25/5;
         System.out.println(data);
      } catch(NullPointerException e) {
         System.out.println(e);
      } finally {
         System.out.println("finally block is always executed");
      }
      System.out.println("rest of the code...");
   }
}

輸出

5
finally block is always executed
rest of the code...

更新於: 2019-07-30

208 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.