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
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.
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(new T)
try
{
//code that uses t
}
catch (...)
{
}
}
The resource allocated via new
will be deleted when the function ends.
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 (...)
{
}
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.