×

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

Loops in C++

A loop statement in most programming languages allows us to execute a statement or a collection of statements numerous times. Control structures of programming languages vary, allowing for more complex...

6 minutes read.

C++ Continue

In C++, the continue statement is a useful tool for avoiding specific scenarios without breaking the loop. It is employed inside loops to move directly to the following iteration and...

4 minutes read.

Difference between "int main( ) and int main(void)" in C/C++

int main( ) function In the C/C++ programming language, int main() indicates a function that returns an integer at the end of the program execution. In general, a value of '0' indicates...

3 minutes read.

Iostream in C++

Using Iostream in C++, we can perform input and output operation capabilities. This represents input and output, and the stream is used to carry out this capability. A stream is...

4 minutes read.

Top 5 IDEs for C++ That You Should Try Once

In the past decades, creating an application or interface from the very basic idea, the developer has to struggle a lot for it. Because an application is a combination of...

3 minutes read.

Multilevel Inheritance

C++ Multilevel Inheritance Multilevel inheritance is such an inheritance in which a derived class is created from another derived class. C++ Multilevel Inheritance Example In this example, a base class Student is inherited in...

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++ find missing in the second array

Given two arrays A and B of sizes n and m. Find the elements from array A that are not present in array B. Example Input : a[] = {1, 2, 3, 5,...

3 minutes read.

Stack in C++

Stack: The stack is a very popular data structure. It is the form of data structure that follows a particular order called FIFO(First-In-First-Out). In simple words, a stack is an Abstract...

4 minutes read.

C++ References

C++ References An alias is a reference variable that is another name for a variable already in existence. If a relation is initialized with a variable, it is possible to use...

3 minutes read.

C++ Dijkstra Algorithm Using the Priority Queue

In this article we will be finding the shortest routes from a source vertex in a graph to all vertices in the graph, given a graph and a source vertex...

5 minutes read.

Sum of all elements between k1’th and k2’th Smallest Elements

In this tutorial, we will look at how to determine sum of all given elements between two given indexes’ smallest elements. Assuming an array of integers and two numbers, k1...

2 minutes read.

Unary Operators in C++

Unary operators in C++ Unary operator: is operations that function to produce a new value on a single operand. a) unary minus: A minus operator modifies the argument's symbol. A positive number...

3 minutes read.

Bit Manipulation in C++

The high-level language in which we communicate is not understood by the computer. As a result, there existed a standard mechanism for understanding any instruction sent to the computer. At...

5 minutes read.

Default arguments in C++

Arguments in a function are defined as the values supplied when the function is called. The source is the values supplied, and the destination is the receiving function. Let us...

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

C++ Algorithms

There are plenty of programming paradigms that are closely associated with the implementations of code and simulate them into a proper functional one. This is done with the help of...

5 minutes read.

Implementation of a Falling Matrix in C++

In many Hollywood and Bollywood movies, we might have seen a programmer who will be referred to as a hacker all the time for some random reason which the writer...

3 minutes read.

Ways to Copy a Vector in C++

Vectors in C++ are the same as arrays, along with additional outstanding features than them, like array lists in Java programming language. In Vectors, the size constraint is eliminated, which...

5 minutes read.

Method overriding in C++

What is method overriding? Using the same function in derived class as their base class is referred to as function/method overriding in c++. Method overriding is an example of polymorphism. With...

2 minutes read.