×

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

How to Setup Environment for C++ Programming on Mac

Mac OS X code Installation There are so many environments available for C++. We are going to install jGrasp and Xcode in our mac operating system. Instruction for installation of jGrasp and...

2 minutes read.

Computing index using Pointers Returned by STL Functions in C++

In this tutorial we will learn how to compute index using pointers which returned by STL functions in C++. Many built-in C++ functions return pointers to memory places that provide...

2 minutes read.

C++ Overloading

C++ Overloading is a condition when two or more members have the same name with different parameter type or a different number of parameter. C++ overloading is two types: Function...

1 minute read.

C++ Program to Implement Shell Sort

    C++ Program to Implement Shell Sort shell sort is basically an Insertion Sort variant. In the insertion sort, we only transfer elements ahead of one location. Many movements are involved...

2 minutes read.

What are local class and global class in C++

In C++, a class is a fundamental block that achieves object-oriented programming. The class holds its data members and member functions. Objects help to access the data elements and functions....

4 minutes read.

Inheritance Program in C++

What is Inheritance? Inheritance is the ability of a class to inherit traits and properties from another class. One of the most crucial aspects of Object-Oriented Programming is inheritance. The ability or...

9 minutes read.

C++ Data Abstraction

Object-oriented programming (OOP) provides a number of characteristics that enable programmers to design programmes based on a variety of ideas, reducing errors and increasing program flexibility. The abstraction of data...

7 minutes read.

Difference between OOP and POP in C++

Object-Oriented Programming (OOP) Prioritizes data over methods (functions) and treats data as an essential component of program development.  OOP prohibits the free flow of data throughout the system. Tighter ties to data manipulation...

4 minutes read.

C++ Installation

Let's install C++ setup to start programming in C++. C++ setup contains C++ compiler which is required in your system. There are lots of C++ compilers available, you must choose...

1 minute read.

Initialize Vector in C++

Initialize Vector in C++  The following comparison operators are defined for vector and those are given below. ==, <, <=, !=, >,>=  This allows you to access the element of a vector using...

3 minutes read.

Factorial Program in C++

C++ Factorial Program: The product of all positive descending integers is the factorial of n. n! denotes the factorial of n. For instance: 5! = 5*4*3*2*1=120 4! = 4*3*2*1=24 In Combinations and Permutations, the...

4 minutes read.

Functors in C++

Functors are not a very popular thing among beginner or intermediate-level programmers. But this thing is very useful and helpful. The name functor suggests us some similarities with function. It...

3 minutes read.

getline() Function and Character Array in C++

In this article, we will explore about some concepts on getline() function and character array in the most useful language C++. The getline() method in C++ is simply a standard library...

6 minutes read.

Armstrong Number using While Loop in C++

What is while Loop? A while loop or while statement repeats all code of its body as long as a specific condition is satisfied. The loop ends if or when the...

4 minutes read.

Scope Resolution Operator vs this Pointer in C++

In this tutorial, we will compare the Scope Resolution operation to this Pointer in C++ language. Scope Resolution Operator The Scope Resolution Operator in C++ programming language is usually denoted by (::)....

3 minutes read.

Division in C++

C++ Division Arithmetic Operation In C++ the arithmetic operator / is used for division. This operator takes two operands and returns the result of dividing the left operand by the right...

3 minutes read.

DES in C++

The popularity of the Data Encryption Standard (DES) is slightly declining as a result of the discovery that DES is susceptible to very strong attacks. Since DES is a block cypher,...

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

This keyword in C++

This keyword in C++ is a pointer which points to the object. It is passed as an argument to functions which helps in accessing the object. It is used for a...

3 minutes read.

Ascending order in C++

In C++, the term "ascending order" refers to a specific order in which a list of elements is arranged. When a list of elements is arranged in ascending order, the...

3 minutes read.