3

I have a method in my Java code that takes a logger as a param. What I need to know is if it is best practice to throw a special exception if the logger passed in is null?

Right now if I test it with a null logger it throws a nasty java.lang.nullPointer exception.

public static void sendLogMessage(Logger logger){
if(logger!=null){
//Do something sweet here
}else{
//throw exception?
}
OrwellHindenberg
  • 4,988
  • 8
  • 38
  • 58
  • 1
    Isn't a `NullPointerException` what you want? – Paul Boddington Nov 12 '15 at 20:28
  • what else could you do? – ergonaut Nov 12 '15 at 20:29
  • @PaulBoddington a team member was thinking it was too generic. I guess I could just create a custom exception that spit something out like "logger was null". I wanted to know if there was an established best practice. – OrwellHindenberg Nov 12 '15 at 20:29
  • 2
    You can do `throw new NullPointerException("Logger was null");`. – Paul Boddington Nov 12 '15 at 20:30
  • 1
    "if I test it with a null logger it throws a nasty java.lang.nullPointer exception." - nasty is the fact that logger is null, I think. "if there was an established best practice" best practice is to use something like NullLogger. – Andrej Istomin Nov 12 '15 at 20:30
  • 1
    It all depends on how **you** or your **company** wants to handle the situation. There is no "right" answer. Maybe you want to still process even if `logger` is `null`...maybe not. Maybe you want a more descriptive error message maybe you don't... – brso05 Nov 12 '15 at 20:31
  • These comments are all true! Think I'll do as @PaulBoddington suggests. Besides that there really isn't anything else to do. it seems we want the extra descriptive-ness so I'll add a tiny blurb for devs. – OrwellHindenberg Nov 12 '15 at 20:34
  • @OrwellHindenberg It's all a matter of opinion really, but personally I don't like creating custom exception types. Everybody understands what a `NullPointerException` is as we've all seen enough of them. – Paul Boddington Nov 12 '15 at 20:35
  • 2
    Interesting question. Personally I've never seen the null-check on the logger. But I am only speaking for myself. In production in general, if the logger is unfortunately null, yet the application can still carry on, to say the least, you lose a lot of valuable data for monitoring and remediation. More importantly, if the logger is never expected to be null yet it is, it may be pointing to a bigger problem with your setup. In either case, stopping the application and having the issue addressed right away seems to be the way to go, which means throwing an exception is not a bad idea. – Hua Nov 12 '15 at 20:35
  • one of my other co-workers suggested returning null where I can or just return if the method is void – OrwellHindenberg Nov 12 '15 at 20:54

0 Answers0