简体   繁体   中英

Java Exception Classes

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, ie

catch(NullPointerException e)
    e.printStackTrace();

So my question is, how are we able to use object reference e without instantiating it?

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...

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.

是的, catch(NullPointerException e)引用e catch(NullPointerException e)是使用throw new NullPointerException("some error message");在代码中throw new NullPointerException("some error message");的可能异常throw new NullPointerException("some error message");

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM