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

📅  最后修改于: 2020-03-29 08:15:52             🧑  作者: Mango

两种语言都使用trycatchthrow关键字进行异常处理,并且trycatchfree块的含义在两种语言中也相同。以下是Java和C++异常处理之间的区别。
1)在C++中,所有类型(包括基本类型和指针)都可以作为异常抛出。但是在Java中,只有对象(Throwable对象是Throwable类的任何子类的实例)可以作为异常抛出。例如,以下类型的代码在C++中有效,但类似的代码在Java中不起作用。

#include 
using namespace std;
int main()
{
   int x = -1;
   
   try {

      if( x < 0 )
      {
         throw x;
      }
   }
   catch (int x ) {
      cout << "异常出现: 抛出的值是 " << x << endl;
   }
   getchar();
   return 0;
}

输出:

异常出现: 抛出的值是 -1

2)在C++中,有一个特殊的捕获称为“全部捕获”,可以捕获所有类型的异常。

#include 
using namespace std;
int main()
{
   int x = -1;
   char *ptr;
   ptr = new char[256];

   try {

      if( x < 0 )
      {
         throw x;
      }
      if(ptr == NULL)
      {
         throw " ptr is NULL ";
      }
   }
   catch (...) // 全部捕获
   {
      cout << "异常出现"<< endl;
      exit(0);
   }
   getchar();
   return 0;
}

输出:

异常出现

在Java中,出于所有实际目的,我们可以捕获Exception对象,以捕获所有类型的异常。因为,通常我们不捕获异常(错误)以外的Throwable。

catch(Exception e){
  …….
}

3)在Java中,有一个名为finally的块,该块总是在try-catch块之后执行。此块可用于执行清理工作。C++中没有这样的块。

// Java展示finally
class Test extends Exception { }
class Main {
   public static void main(String args[]) {
      try {
         throw new Test();
      }
      catch(Test t) {
         System.out.println("有异常");
      }
      finally {
         System.out.println("在finally内 ");
      }
  }
}

输出:

有异常
在finally内

4)在C++中,所有异常均unchecked。在Java中,有两种异常类型:checked和unchecked。
5)在Java中,新的关键字throws用于列出函数可以抛出的异常。在C++中,没有throws关键字,为达到此目,使用了相同的关键字throw