C graphics
C graphics

Reputation: 7458

Java: is this necessary while catching exception?

eWhile catching exceptions is this necessary to check if the error message is not null to avoid null pointer exception? Another words, is the if (e!=null) part needed? or e is always not null?

 try {
     ...

  } catch(Exception e) {
     if (e != null) {
        System.err.println("Error: " + e.getMessage());
     }

  }

Upvotes: 3

Views: 167

Answers (4)

CrazyCasta
CrazyCasta

Reputation: 28302

Anything that gets thrown must be a subclass of Throwable, and your catch will only catch things that are a subclass of Exception. Therefore you can neither throw nor catch null, therefore checking for nullality is not necessary. If you use throw null or throw a variable that contains null then it will throw a NullPointerException.

Upvotes: 9

didster
didster

Reputation: 882

e will never be null. Even if you throw null (which is perfectly legal) java will convert that into a NullPointerException as detailed in the spec here

Upvotes: 3

user1448458
user1448458

Reputation:

The caught exception will never be null as it is been already caught. So the check:

if (e != null) { }

Is absolutely not necessary.

Upvotes: 1

Brad
Brad

Reputation: 1529

The exception will never be null. However, some properties of the exception could be null.

Upvotes: 3

Related Questions