Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Exception vs C++ Exceptions

Where are exceptions stored ? Stack, Heap. How is memory allocated and deallocated for Exceptions? Now if you have more than one exception which needs to be handled are there objects of all these exceptions created?

like image 712
Thunderboltz Avatar asked May 08 '09 06:05

Thunderboltz


People also ask

How is exception handling in C and Java?

Master C and Embedded C Programming- Learn as you goOnly throwable objects can be thrown as objects. In java, finally is a block that is executed after try catch block for cleaning up. A new keyword throws is used to list exceptions thrown by a function.

Are C++ exceptions slow?

We know that exceptions are really slow, and if you're programming in C++, you generally don't want slow — especially for general flow control error handling. Exceptions are also hopelessly serial, meaning they must be dealt with immediately, and they do not allow for storing of an error to be handled at a later time.

What is the difference between Java error and an exception?

Errors are usually raised by the environment in which the application is running. For example, an error will occur due to a lack of system resources. Exceptions are caused by the code of the application itself. It is not possible to recover from an error.

What are the three types of exceptions?

There are three types of exception—the checked exception, the error and the runtime exception.


1 Answers

I would assume that memory for exceptions is allocated the same way as for all other objects (on the heap).

This used to be a problem, because then you cannot allocate memory for an OutOfMemoryError, which is why there was no stack trace until Java 1.6. Now they pre-allocate space for the stacktrace as well.

If you are wondering where the reference to the exception is stored while it is being thrown, the JVM keeps the reference internally while it unwinds the call stack to find the exception handler, who then gets the reference (on its stack frame, just like any other local variable).

There cannot be two exceptions being thrown at the same time (on the same thread). They can be nested, but then you have only one "active" exception with a reference to the nested exception.

When all references to the exception disappear (e.g. after the exception handler is finished), the exception gets garbage-collected like everything else.

like image 146
Thilo Avatar answered Nov 15 '22 16:11

Thilo