• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

Why set an object to null in its delcaration?

 
Ranch Hand
Posts: 441
Scala IntelliJ IDE Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There's an example in Head First Java (p. 393) that involves a static utility method reproduced below...



My question is, why is "event" set to null at the start? Why not just stick "MidiEvent" in front of the line where event's value is assigned? I've seen people setting object declarations to "null" before... why would you do this?

 
Luigi Plinge
Ranch Hand
Posts: 441
Scala IntelliJ IDE Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
... in their example on page 388 it's static, but on page 393 I've just noticed it's not... not sure whether being static has something to do with declaring it as null?
 
author
Posts: 23928
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Why set an object to null in its delcaration?



In my opinion, this is mostly done for code where there is a route that doesn't set the variable. And the compiler is complaining about it.

Henry
 
Bartender
Posts: 4179
22
IntelliJ IDE Python Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
At line 10 in your code the event is returned. Which means the scope of the variable has to be beyond the try{} block. If you declared the variable where it gets assigned in line 6, then by the time you need to return it, the variable would not be accessible - it would have gone out of scope with the closing of the curly braces at the end of the try block.
 
Greenhorn
Posts: 3
Mac OS X Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
# public static MidiEvent makeEvent(int comd, int chan, int one, int two, int tick){
# MidiEvent event = null; // ???
# try {
# ShortMessage a = new ShortMessage();
# a.setMessage(comd, chan, one, two); <-- this could thrown an exception so in that case
# event = new MidiEvent(a, tick);
#
# } catch (Exception e) {
# }
# return event; <-- what am i trying to return?
# }

the method is marked to return a object of type MidiEvent so any class that calls this method will expect some thing in return either a event or null ;
since the try block allows the option to throw exceptions, we might end up in the return statement with event not pointing to anything so this causes the compile error.
 
Luigi Plinge
Ranch Hand
Posts: 441
Scala IntelliJ IDE Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
OK I think I get it now. I didn't understand before that if you declare something in a try block, it goes out of scope outside it. Also, if the try block fails, we need to have set "event" to something or it won't compile.

Here's the version I actually coded (was trying to do the example without looking at their solution)



but I suppose this works a bit differently because it'll return an incorrectly set MidiEvent if the setMessage(..) method fails, rather than null. Then again, I could just put "return null;" in the catch block and it should work the same.
 
Saloon Keeper
Posts: 14515
325
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I realize this is just for testing purposes, but I would like to press you to never use the try-catch blocks the way you do, in a real life program.

First of all, never catch Exception. It will catch Runtime exceptions as well, and you shouldn't catch those.
Secondly, never have an empty catch block. Even if there's nothing you want to do in the block, at least print a message or log the exception.
 
Luigi Plinge
Ranch Hand
Posts: 441
Scala IntelliJ IDE Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Stephan van Hulst wrote:
First of all, never catch Exception. It will catch Runtime exceptions as well, and you shouldn't catch those.


OK... I haven't heard this one before. They catch Exception all throughout the examples in Head First Java... but then they also just put "ex.printStackTrace();" in the catch block, which my IDE warns me I shouln't do. I guess I should find out the specific class or classes of checked exceptions that will be thrown.

Secondly, never have an empty catch block. Even if there's nothing you want to do in the block, at least print a message or log the exception.


OK will do!
 
Stephan van Hulst
Saloon Keeper
Posts: 14515
325
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well, I can imagine it would be nicer to catch Exception right away, in a book like that, because I suppose they want to distract as little as possible from the actual lesson they're trying to teach you.

It doesn't really matter that much in experiments or tests or something like that, but if you write code for an actual project, you should avoid catching any runtime exception, including their superclasses (RuntimeException, Exception and Throwable).
 
Rancher
Posts: 4335
59
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Stephan van Hulst wrote:I realize this is just for testing purposes, but I would like to press you to never use the try-catch blocks the way you do, in a real life program.
First of all, never catch Exception. It will catch Runtime exceptions as well, and you shouldn't catch those.


I have no problem with saying programmers should usually avoid this in most cases. But there are times when it's perfectly legitimate to catch RuntimeException or Exception. Occasionally even Throwable, though that's more controversial.

Even if a RuntimeException often (not always) signals a programming error that the programmer should really fix elsewhere in code, well, the reality is that it's often not realistic to expect that all such problems have been detected before we ever try to run the code. Consequently, it's often a good idea to try to handle the possibility that the code does still contain programming errors, which we'll want to fix ASAP after we discover them. But until that fix occurs, it may still be reasonable to (a) log the error, and (b) move on the next record/job/request/whatever that we need to process, without letting that programming error completely shut down the application. In order to achieve this, it's reasonable to use a catch (Exception e) block. In my opinion, of course.

Stephan van Hulst wrote:Secondly, never have an empty catch block. Even if there's nothing you want to do in the block, at least print a message or log the exception.


This I agree with, absolutely.
 
Sheriff
Posts: 67682
173
Mac Mac OS X IntelliJ IDE jQuery TypeScript Java iOS
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Stephan van Hulst wrote:Secondly, never have an empty catch block. Even if there's nothing you want to do in the block, at least print a message or log the exception.


Or, a comment on why you are eating the exception. For example, a parsing exception while converting a String to an int doesn't need to be logged or generate a message. But the block should never just be left empty. If it is appropriate to leave it empty, put in a comment explaining why!
 
BWA HA HA HA HA HA HA! Tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic