Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between exception handling in C++ and Java?

Tags:

In Java, if a specific line of code causes the program to crash, then the exception is caught and the program continues to execute.

However, in C++, if I have a piece of code that causes the program to crash, like:

try {     int x = 6;     int *p = NULL;     p = reinterpret_cast<int*>(x);      *p = 10; // the program crashed here      cout << "x = " << *p << endl; } catch(const char* Message) {     cout << "There is an run-time error"; } 

Then the program still crash and the exception is not caught.

So what is the point of exception handling in C++? Am I misunderstanding something?

like image 229
ipkiss Avatar asked Sep 20 '11 04:09

ipkiss


People also ask

Is there any exception handling in C?

The C programming language does not support exception handling nor error handling. It is an additional feature offered by C. In spite of the absence of this feature, there are certain ways to implement error handling in C. Generally, in case of an error, most of the functions either return a null value or -1.

What is the difference between the exception handling in C and C++?

Exception Handling in C++ One of the advantages of C++ over C is Exception Handling. Exceptions are runtime anomalies or abnormal conditions that a program encounters during its execution.

What are different exception handling in Java?

Java Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc. Exception is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at run time, that disrupts the normal flow of the program's instructions.

What are the advantages of using exception handling in Java?

Advantage 1: Separating Error-Handling Code from "Regular" Code. Exceptions provide the means to separate the details of what to do when something out of the ordinary happens from the main logic of a program. In traditional programming, error detection, reporting, and handling often lead to confusing spaghetti code.


1 Answers

The line that crashes is dereferencing an invalid pointer. In C++ this will not throw an exception. Instead it is undefined behaviour.

There's no such thing as a null pointer exception in C++, unlike Java which will throw a null pointer exception. Instead dereferencing an invalid pointer will lead to undefined behaviour. Undefined behaviour does not always imply a crash, however if it crashes you're lucky.

Language overview:

Finally and RAII

One of the most significant differences between C++ and Java is that Java supports a finally statement. Code in the finally block is always run regardless of whether code in the preceding catch block is executed or not. For example:

try { } catch (SomeException e) { } finally {   //code here is always exectued. } 

The purpose of the finally statement is to allow the programmer cleanup at that point, i.e. release sockets, close file handles etc... Even though Java runs a garbage collector, garbage collection only applies to memory and no other resource. There are still occasions where you have to manually dispose of resources. Now C++ doesn't have a finally statement so users of the language are advised to adhere to the RAII principle (Resouce Acquisition is Initialization) Stroustrup has an explanation about it here: http://www.stroustrup.com/bs_faq2.html#finally. I prefer to call it Resource destruction is deallocation but basically when your object falls out of scope, invoking the destructor, then that destructor should release whatever resources the object maintained.

For example, C++11x provides a std::unique_ptr to manage this:

void foo() {   std::unique_ptr<T> t(new T)   try   {     //code that uses t   }   catch (...)   {   } } 

The resource allocated via new will be deleted when the function ends.

catch all statements

Because all exceptions in Java inherit from a common base class Exception if you want your catch clause to catch any exception, then set it up like this:

catch (Exception e) {   //any exception thrown will land here. } 

In C++ there's no restriction on what can be thrown and no common base class for all exceptions. Standard practice is to form your custom exception class by inheriting from std::exception but the language doesn't enforce this. Instead there's a special syntax for catching all exceptions:

catch (...) {  } 

Unhandled exceptions

This is another area where the languages behave differently. In C++ a thrown exception that is not caught will call std::terminate. std::terminate's default behaviour is to call abort which generates a SIGABRT and the entire program stops.

In Java the behaviour is to print a stack trace and terminate the thread that the uncaught exception occured in. However because a Java programmer may provide an UncaughtException handler, the behaviour could quite well be different from the default of terminating the thread.

like image 74
sashang Avatar answered Oct 23 '22 04:10

sashang