Comparison of Exception Handling in C++ and Java


The exception handling feature is present almost any object oriented languages nowadays. In C++ and Java also we can get this kind of feature. There are some similarities between exception handling in C++ and exception handling in Java, like in both languages we have to use the try-catch block. Though there are some difficulties also. These are like below −

In C++, we can throw any type of data as exception. Any type of data means primitive datatypes and pointers also. In Java we can only throw the throwable objects. Subclasses of any throwable class will also be throwable.

Example

 Live Demo

#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;
   }
}

Output

Exception Caught: thrown value is -5

In C++, there is an option called catch all to catch any type of exceptions. The syntax is like below −

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

Example

 Live Demo

#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;
   }
}

Output

Exception Caught

In Java if we want to catch any type of exception, we have to use the Exception class. Which is the super class of any exception present in Java, or some user defined exceptions also. The syntax is like below −

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

The C++ has no finally block. But in Java there is one special block called finally. If we write some code in finally block, it will be executed always. If try block is executed without any error, or the exception occurs, the finally will be executed all of the time.

Live Demo For Java

Example

 Live Demo

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...");
   }
}

Output

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

Updated on: 30-Jul-2019

161 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements