Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IntelliJ IDEA doesn't highlight the code which throws an exception - how to turn it on?

I have a method:

private void test() throws NullPointerException {
        System.out.println("blabla");
        throw new NullPointerException();
    }

which throws NullPointerException but when I'm trying to invoke this method:

test();

IntelliJ IDEA doesn't warn me that it throws NullPointerException. IntelliJ should warn me about this, right?

I found out that there are turned on/off inspections in Settings -> Editor -> Inspections but I couldn't find this inspection.

How to turn it on?

@edit

Alright, I learnt that NullPointerException is a type of an exception which IntelliJ won't highlight because this is kind of critical error. Other exceptions like IOException are being highlighted. But still, is it possible to turn highlighting NullPointerException on?

like image 523
Defozo Avatar asked Mar 12 '23 16:03

Defozo


1 Answers

Thanks to your edit, it's easier to explain the behavior you're seeing. IntelliJ flags Exceptions that do not subclass java.lang.RuntimeException because that is an actual compilation error.

Let's look at the JavaDoc for Exception:

The class Exception and any subclasses that are not also subclasses of RuntimeException are checked exceptions. Checked exceptions need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.

... And the JavaDoc for RuntimeException:

RuntimeException and its subclasses are unchecked exceptions. Unchecked exceptions do not need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.

In other words, you can throw a RuntimeException overtly in your code, and you don't necessarily have to declare it or catch it, and your compiler will be perfectly happy with that (although your API's users might not be so jolly). On the other hand, Exceptions that do not subclass RuntimeException are called "checked" exceptions, and must either be declared as thrown by your methods or caught and handled when they might occur, in accordance with the language's specifications.

(P.S., if you didn't catch it yet, NullPointerException is a RuntimeException. Hence, it is unchecked.)

like image 66
nasukkin Avatar answered May 01 '23 09:05

nasukkin