×

Exception Handling in C++ vs Java

Nowadays, exception handling is a feature found in virtually all object-oriented languages. We can also find this type of feature in Java and C++. The try-catch and block is required in both languages for managing exceptions, which is a comparable need for both C++ and Java. The terms to try, catch, and block are used for exception handling in both languages, and they also have the same meaning in both languages. Even so, there are certain challenges.

The following points outlines how Java and C++ handle exceptions differently :

Java :

  • As an exception, only throwable objects may be hurled.
  • To handle any error, we may capture Exception objects. Because we typically only catch Exception-related Throwable(s).
  • After the try-catch block, an additional special block known as finally is always carried out.
  • Checked and unchecked exceptions are the two different sorts.
  • In order to list the exceptions that a function may throw, use the special term throws.
  • In Java, finding and managing the exception is simpler.

C++ :

  • Any type may be raised as an exception.
  • All sorts of exceptions can be caught with an unique catch called "catch all."
  • Such(finally) a block doesn't exist in C++.
  • There are no exceptions selected.
  • The exceptions which could be thrown by a function are listed using the term throw.
  • In C++, locating and managing the exception is fairly challenging.

Following is a detailed discussion of the aforementioned points:

1) In C++, exceptions can be thrown for any type, including primitive and pointer types. But only throwable objects—which are instances of any Throwable class subclass—can be thrown as exceptions in Java. For instance, the given type of code is valid in C++ but invalid in Java.

Example :

// CPP Program for illustrating all the types (like primitive
// and pointer) could be thrown as exceptions.
#include <iostream>
using namespace std;
int main()
{
	int a = -5;


	// some other kind of stuff
	try {
		// some other kind of stuff
		if (a < 0) {
			throw a;
		}
	}
	catch (int a) {
		cout << "Exception has occurred : the thrown value is " << a
			<< endl;
	}
	getchar();
	return 0;
}

Output :

Exception has occurred : the thrown value is -5

2) The "catch all" function in C++ is a particular catch all method that can handle any exception.

Example :

// CPP example to illustrate catch all functions
#include <iostream>
using namespace std;
int main()
{
	int a = -43;
	char* pntr;


	pntr = new char[256];


	try {


		if (a < 0) {
			throw a;
		}
		if (pntr == NULL) {
			throw " the pntr is NULL ";
		}
	}
	catch (...) // catch all function
	{
		cout << "Exception has occurred: now exiting " << endl;
		exit(0);
	}


	getchar();
	return 0;
}

Output :

Exception has occurred: now exiting

For all intents and purposes, we can capture exceptions in Java using Exception objects. Because we typically just catch Exception(s) and Throwable(s) (which are Errors)

catch(Exception exp){
 //something
}

3) After the try-catch and block in Java, a block known as finally is always run. Cleaning up may be done with this block. Such a block doesn't exist in C++.

Example :

// Java Programme to illustrate the creation of an exception type
class Testing extends Exception {
}


class Main {
	public static void main(String argmnts[])
	{


		try {
			throw new Testing();
		}
		catch (Testing x) {
			System.out.println("Received the Testing Exception");
		}
		finally {
			System.out.println("\nInside the finally block ");
		}
	}
}

Output :

Received the Testing Exception
Inside the finally block

4) All exceptions in C++ are unchecked. Checked and unchecked exceptions are both available in Java.

5) A new term called throws is used in Java to list the exceptions that a function may throw. There exists no throws keyword in C++, instead, the term throw is used in this context.

6) In C++, if the exception isn't handled, the function unexpected() is called, which causes an improper programme or application termination. Finding a specific exception that occurs in our C++ software takes a lot of effort since unexpected() in C++ does not inform us what type or line the exception has happened on. In contrast, Java's runtime system (JVM) hands away the exception object to the default exception handler if the system-generated exception isn't handled. This default exception handler merely publishes the name, description, and line number where the error occurred. Therefore, it is simpler to identify and handle exceptions in Java than it is in C++.


Related Topics

Difference between Two Sets in C++

The distinction between the two sets is made up of the components that are present in the first set but absent from the second set. The function consistently duplicates the...

3 minutes read.

Features and Use of Pointers in C/C++

What is a pointer? A pointer is mainly used to store the address of another variable. The * operator creates a pointer variable, which points to a data type (like an...

7 minutes read.

C++ Program to find the largest number formed from an array

Given an array, write a program to find the largest number that will be formed from the elements of the array. Arrangement should be done in such a way that...

4 minutes read.

Passing by Reference Vs. Passing by the pointer in C++

 Passing by Reference Vs. Passing by the pointer in C++ Throughout C++, it can transfer parameter values except by pointers or through referring to a function. For both cases, we have...

3 minutes read.

Armstrong number using for loop in C++

What is For Loop? A for loop is a repetitive control structure that allows you to create a loop to execute a specific number of times efficiently. The syntax that can be...

4 minutes read.

Check for Balanced Brackets in an Expression (well-formedness) using Stack

Write a program that check the correctness of the pairs and ordering of the characters “{“, “}”, “(“, “)”, “[“, “]” in the expression string exp. Example: Checking for balanced parenthesis is one of...

2 minutes read.

Difference between exit() and _Exit() in C++

Before understanding the difference between the exit() and _Exit(), one must know about exit() and _Exit() functions. The exit() function in C/C++ The exit() method in the C language kills the calling...

3 minutes read.

C++ Friend function

A friend function has the right to access all private and protected members of a class although it is defined outside that class' scope. Syntax class className{     ......     friend retyrn_type function_Name(argument);     .......   }   return_type function_Name(argument){     ......   } C++ friend function Example #include <iostream>   using namespace std;   class Length   {       private:           int meter;       public:           Length(): meter(5) { }           friend int addMethod(Length); //friend function declaration   };   int addMethod(Length l) // friend function definition   {       l.meter += 10; //accessing private data from non-member function       return l.meter;   }   int main()   {       Length L;       int totallength;       totallength=addMethod(L);       cout<<"Length: "<< totallength;       return 0;   } Output: Length: 15   C++ friend function...

1 minute read.

Decimal to Binary in C++

What is the meaning of Decimal Numbers? Decimal numbers range from 0 to 9, there are a total of ten digits between 0 and 9. Any number with more than two...

3 minutes read.

Array program in C++

What is an Array? An array is a set of identically typed elements that are organized into contiguous memory locations and each element can be independently accessed using an index. We can...

16 minutes read.

Virtual base class in C++

Consider in a C++ program, there are 4 classes named class A, class B, class C, and class D. If class B and class c inherit properties from class A....

3 minutes read.

C++ Bitwise XOR Operator

Exclusive OR is another name for the bitwise XOR operator. The ‘^’ is used to indicate it. It operates at the bit level of the operands, as the name implies....

4 minutes read.

How to call a void function in C++

Generally, any function has two types: 1. Void function: It doesn't return any value. 2. Non-void function: It returns some value. Program to call a void function in C++ #include <iostream> using namespace std;  void check() {  ...

2 minutes read.

Reverse String Word-Wise in C++

What is a reversed String? Reversing the words of a sentence is called reversed string by words. The difference between the reverse a string and the reverse a string word-wise is...

4 minutes read.

Divide by Zero Exception in C++

We use exception handling method to handle the divide by zero exception. Dividing a number with zero is generally mathematical error. We have to exception handling method to overcome this...

2 minutes read.

Inheritance and Friendship in C++

In this tutorial, we will look into what Inheritance and Friendship in C++ are, as well as the differences between the two. What is Inheritance in C++: In C++, inheritance is an...

2 minutes read.

Virtual Function Vs Pure Virtual Function

Virtual activity is a member function defined in the foundation phase that can be redefined by acquired classes. Let's have a look at an example: #include <iostream>   #include <bits/stdc++.h> #include <stdlib> using namespace std;   class Base   {    ...

5 minutes read.

Free vs delete() in C++

Free vs delete() in C++ In this section, we will learn about the free() function and also create a C ++ program of the delete operator. What is free() Function in C++? In...

4 minutes read.

C++ Program to find largest subarray with 0 sum

Write a program to find the largest subarray that has a sum zero. The array contains positive and negative numbers. Print the length of the max subarray whose sum turns...

4 minutes read.

Reverse a String using Stack C/C++

Reverse the given string using stack. To turn "tutorialandexample" into "elpmaxednalairotut," for instance. Here is a straightforward stack-based technique for reversing strings. Algorithm: 1) Make a stack that is empty. 2) Push each character...

3 minutes read.