Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Exception Handling in C++:
3.
Exception Handling in JAVA:
4.
Difference between C++ and Java exception handling:
4.1.
Exception handling in C++
4.1.1.
Code:
4.1.2.
Code:
4.2.
Exception Handling in Java
4.2.1.
Code:
5.
FAQs:
6.
Key Takeaways:
Last Updated: Mar 27, 2024
Easy

Exception Handling in C++ and Java

Author Ankit Kumar
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Exception Handling is one of the essential features which tells the compiler how to handle an exception in the program. And in this article, we will discuss Exception Handling in C++ and JAVA, their differences, and a few programs to validate the points.

As the name suggests, Exception Handling is a way to handle run-time errors so that the remaining code works correctly. It can be varied in different programming languages, but in C++ and Java, they use the exact keywords: try, catch, and throw. Also see, Literals in C.

Let's see a brief explanation about Exception Handling in C++ and Java:

Exception Handling in C++:

When a code executes, there can be a possibility of an error. The error can be of anything, maybe a bug on the program, some input error or anything that will stop the entire program and display an error message called throwing an exception.

Exception handling in C++ consists of three keywords: try, throw and catch.

The try statement will allow us to write a piece of code to be tested for error at the time of execution.

The throw keyword will throw an exception when the exception is detected.

The catch statement contains code that will be executed if the try statement throws an error.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Exception Handling in JAVA:

Exception handling in Java is the method to handle the run-time error and is the most efficient method to handle an exception. There are various types of errors that generally occurs during execution. Some are ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Java's exception handling contains the same three keywords try, throw, and catch. And their functioning is the same as it is in C++.

Now we will see some differences between exception handling in C++ and Java.

Fibonacci Series in C++

Difference between C++ and Java exception handling:

Following are the differences between exception handling in C++ and Java: 

C++ JAVA
All types can be thrown as exceptions Only throwable objects can be thrown as an exception
Has a ‘catch all’ block to catch all kinds of exceptions Does not have a ‘catch all’ block
Throw keyword is used to list exceptions thrown by a function Throws keyword is used to list exceptions thrown by a function
Finally block does not exist. Finally block exists, used after try-catch for clean up.
Only unchecked exceptions are present Both checked and unchecked exceptions are present
Exception handling in C++ is a little bit difficult Exception handling in Java is easier than in C++.

These are some differences between exception handling in C++ and Java.

Now we will understand the exception handling through code both in C++ and Java.

Exception handling in C++

Code:

#include <iostream>
using namespace std;
int main()
{
int temp = 0;
try {
if (temp < 1) {
throw temp;
}
}
catch (int temp) {
cout << "Exception occurred at value " << temp << endl;
}
getchar();
return 0;
}

Output for the given code is

Exception occurred at value 0

And, as one of the differences mentioned, any type of exception can be thrown; this wouldn't work on Java.

Now, let's have a look at the catch-all block in C++:

Code:

#include <iostream>
using namespace std;
int main()
{
int temp = 0;
char* ptr;
ptr = new char[256];
try {
if (temp < 1) {
throw temp;
}
if (ptr == NULL) {
throw " ptr is NULL ";
}
}
catch (...) 
{
cout << "Exception occurred" << endl;
exit(0);
}
getchar();
return 0;
}

The output of the above code is 

Exception occurred

Now let's have a look at exception handling in Java.

Exception Handling in Java

Code:

class Test extends Exception {
}
class Main {
public static void main(String args[])
{
try {
throw new Test();
}
catch (Test t) {
System.out.println("Test exception");
}
finally {
System.out.println("Inside finally block ");
}
}
}

Output for the above Java program that contains the finally block.

Test exception

Inside finally block

These were some exception handling examples in Java and C++. Try and compile with online c++ compiler.

Let us see some frequently asked questions related to the topic.

Must Read Dynamic Binding in C++

FAQs:

  1. What is an exception?
    An exception is an unexpected event that occurs during the execution of a program that is at run-time.
  2. What is an error?
    Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError, AssertionError etc.
  3. What is exception handling?
    Exception Handling is a way to handle run-time errors so that the remaining code works correctly.
  4. What is the finally block?
    Java finally blocks a block used to execute necessary code, such as closing the connection.
  5. What are the keywords for handling an exception in Java?
    Keywords that we generally use are Try, Throw, and Catch. But we often use finally and throws accordingly.

Let us summarize the article.

Key Takeaways:

In this article, we have extensively discussed exception handling in C++ and Java. At first, we have seen some brief explanations about exception handling in C++ and Java separately. Then we discussed differences between them. And at last some programs as an example of exception handling.

C++ vs Java

Also check out this article - Pair in C++

Ninjas! Do not stop here. Learn more about Exception Handling.

We hope that this blog has helped you enhance your knowledge regarding Software Virtualization in cloud computing. If you would like to learn more, check out our articles on Coding Ninjas Studio. Do upvote our blog to help other ninjas grow. Happy Coding!

Previous article
What is an Exception Handling?
Next article
Stack unwinding in C++
Live masterclass