Why is it possible to do throw null; when handling exceptions" in Java?

Asked 1 years ago, Updated 1 years ago, 145 views

public class WhatTheShoot {

    public static void main(String args[]){
        try {
            throw null;
        } } catch (Exception e){
            System.out.println(e instanceof NullPointerException);
            System.out.println(e instanceof FileNotFoundException);
        }
    }
}

Run the code above

true  
false

That's the result. I thought there would be a compilation error, but it was amazing that it was compiled well. Why can you throw null as an exception in Java? And why is it cast as NullPointerException?

java exception-handling nullpointerexception

2022-09-22 22:28

1 Answers

Null appears to be treated as NullPointerException, but it is not. The reason why null appears to be cast as NullPointerException is because This is because the code itself, throw null, calls the result of throwing the nullPointerException.

In other words, throw is to check if the factor is not null and then torow the nullPointerException when it is null.


2022-09-22 22:28

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.