Mike
Mike

Reputation: 23

Exception created Object

I am new to java. I was reading java from sun website. It says,

When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred.

My question is,

  1. Who creates this exception object ?
  2. Whether it is created on the heap, since it is said to be an exception object ?

EDIT : I didn't understand this term "When an error occurs within a method, method creates an object' ?"

Thanks.

Upvotes: 2

Views: 2426

Answers (3)

ThomasRS
ThomasRS

Reputation: 8287

Your Java code is running on a virtual machine; there is more going on than just the code you are writing. The Java SDK throws exceptions.

Exception handling is done in such a way that linear execution of the code is interrupted, and exception flow instead kicks in. Exception flow is basically the exception being 'thrown' until some construct 'catches' it.

    try {

       ... some code is executed 
       ... some code throws exception (throw new Exception())
       ... some more code is never executed
    } catch(Exception e) { // CATCHES
       // code executed in case exception is caught
    } finally {
      // code that runs regardless of above exceptions
    }

If catching does not make sense in some local scope, methods can propagate exceptions like this:

public void doSomeWork(..) throws Exception {

}

and the exception can be caught elsewhere, i.e. higher up in logic. Exceptions also are normal objects, and subclasses (finer details) can be caught before superclasses etc.

There is no stack and heap in the traditional sense in Java, so don't worry about that for now - later you can set some memory management parameters for the JVM as a whole, but the nature of those will normally not be reflected in your code.

Upvotes: 0

Bozho
Bozho

Reputation: 597114

  1. The exception object is created by:
    • you or a method that you invoke in a library that you use, by throw new SomeException()
    • the jvm in some cases (NullPointerException, array size problems, etc)
  2. As every object it is stored in the heap

Upvotes: 4

Etienne de Martel
Etienne de Martel

Reputation: 36852

Basically, you create it.

throw new Exception(); // notice the new

Like any Java object, it is allocated on the JVM heap.

Upvotes: 0

Related Questions