Reputation: 165
I am new to Java and I was looking at exception handling. When we catch java exceptions, we declare and use an Object
of the Exception
class without initializing it, i.e.
catch(NullPointerException e)
e.printStackTrace();
So my question is, how are we able to use object reference e without instantiating it?
Upvotes: 7
Views: 1328
Reputation: 2166
The exception is instantiated. It happens internally in the class that can potentially throw an exception. For your information, the keyword throw is responsible to create and throw the exception. Your catch method will catch the exception. You can also implement your own exceptions using this keyword.
Upvotes: 0
Reputation: 493
Yes, reference e
in catch(NullPointerException e)
is for the possible exception thrown in code using throw new NullPointerException("some error message");
Upvotes: 0
Reputation: 37813
They are well instantiated:
void example() {
throw new UnsupportedOperationException("message");
} // ^^^
void demonstration() {
try {
example();
} catch (UnsupportedOperationException e) {
e.printStackTrace();
}
}
This very simple example should be pretty self explanatory...
Upvotes: 8
Reputation: 83527
The exception is (often) instantiated when the error occurs with a throw
statement. For example,
throw new NullPointerException();
(Note that this is just an example. NPEs are not usually explicitly thrown in your own code.)
The catch
clause is similar to a function that declares a parameter. Consider the function
void func(String s) {
// ...
}
func
does not instantiate the s
. The String
is created somewhere else and passed to the function. In the same way, we create an exception with throw
and it is "passed" to the catch
clause kind of like a parameter.
Upvotes: 1