C ++和Java中异常处理的比较

如今,几乎所有面向对象的语言都具有异常处理功能。在C ++和Java中,我们也可以获得这种功能。C ++中的异常处理和Java中的异常处理之间有一些相似之处,例如在两种语言中,我们都必须使用try-catch块。虽然也有一些困难。这些如下-

在C ++中,我们可以将任何类型的数据作为异常抛出。任何类型的数据都意味着原始数据类型和指针。在Java中,我们只能抛出throwable对象。任何throwable类的子类也将是throwable。

示例

#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...