This week's book giveaway is in the HTML Pages with CSS and JavaScript forum.
We're giving away four copies of Testing JavaScript Applications and have Lucas da Costa on-line!
See this thread for details.
Win a copy of Testing JavaScript Applications this week in the HTML Pages with CSS and JavaScript forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

Garbage Collection

 
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all...
While code review we got into this debate which i am posting now...
in many parts of our code, we have something like this...

Almost for all the objects, we first instantiate the object to null and in the try block we then assign it to some value.
QUESTION:
CORRECT ME IF I AM WRONG HERE
The garbage collector is a low priority thread that runs at the background and always checks for objects that do not have any refernces (or objects that point towards null). In my code mentioned above, is there any chance for the garbage collector to run before i enter the try block?? In such a case will my objects (here String and Vector) objects be garbage collected? If this also happens, will my code bomb??
We could not come to any end to this discussion.
If anyone can clarify this..we shall be grateful
Thanks and Regards,
ganp.
 
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You might find the article Pass-by-Value Please a useful read.
In short your answer is no, it's totally OK. It's objects that get garbage collected and not variables or object references. What you have initially is a reference to a 'nothing' object, then you make it reference a Vector object. That Vector object is referenced by your variable. If you change things so that there is no longer anything refering to you Vector object, the Vector object will become eligable for collection. The variable is fine.
On a side note, (IMO) catching exceptions should not be a substitute for good coding.
Dave.
[This message has been edited by David O'Meara (edited May 11, 2001).]
 
Ganapathi Srinivasan
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi David,
Thanks for that reply...it did help a lot.
But one more thing..in case if we do not assign it to null, the compiler gives an error. Why is that so?


On a side note, (IMO) catching exceptions should not be a substitute for good coding.
[\quote]
We do not catch exceptions to just escape..we need to do it as our applications do talk with a monitoring agent and in case of any unexpected exceptions, the agent is indeed alerted and appropriate actions are taken...so it is just a pre caution and not a coding practice for us. this is FYI.
Thanks and Regards,
Ganp.

 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No doubt others will have opinions when they wake up, but if I don't know the initial value for an object I always initialise it to null. I've seen ppl initialise them to empty objects but thats a useless operation since all you and up doing is creating short lived objects .
Back on the exception catching thread, yesterday I saw this in some production code I was checking:

I'm not sure why that code turned up that way, it might have been a side-effect of unit testing, but essentially it's just lazy
 
author
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Originally posted by Ganapathi Raman:
But one more thing..in case if we do not assign it to null, the compiler gives an error. Why is that so?


Because it is a potential source of bugs. The Java compiler analyses your code paths and ensures that it is impossible for you to access an uninitialised variable. An uninitialised variable would essentially have a random value, and in the vast majority of cases that would be a bug.
In your specific case, the scope of your variables is the entirety of testMethod. If any of the assignments in your try block threw an exception, you would be able to access an uninitialised variable from the catch clause onwards.
- Peter
 
Ganapathi Srinivasan
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Peter and David,
Thanks for ur thoughts..
I do also have one point of contention..As David pointed out it is in case of exception handling.
I find that lots of people insist on catching every possible exception in ur piece of code. Especially in private methods, I am told to cath for java.lang.RuntimeException and so on..the list is endless.
Is it a neat way of coding to catch so many exceptions or is it just laziness in ensuring that everything can be coded perfectly and ruling out any possibility of exceptions occuring in ur code?
Where is this Thin Red Line in case of exceptions in Java?
Regards,
Ganp.
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Once again this is classed 'IMHO', but I believe that you only catch an exception if you know how to deal with it or you are just going to ignore it. Either way you have gobbled the exception and flow continues from that point.
Otherwise you specify that the method throws that exception and let it be handled at a higher level by something else.
I can't believe that it is a good idea to catch a generic exception 'just in case' it get thrown. How do you know what exception was thrown or how to handle it?
Possibly the top point of your code should wrap your entire program in a try/catch to stop exceptions being thrown to the user and so you can pop up a box 'Oops, something failed', but otherwise not.
Dave.
 
Peter den Haan
author
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'd like to second David there. At each level (class) in your application, for each foreseeable exception (which should be roughly equivalent to: for each checked exception), you should ask yourself: what needs to happen when this error occurs? If you don't know, or if it depends, or if what needs to happen is controlled at a different level, you should not catch the exception.
For example, your answer could be "if my class throws a ThisDatabaseIsAPieceOfCrapException, I cannot continue my work in any way but I guess I want an error box to pop up telling the user to buy another database". This suggests that the ThisDatabaseIsAPieceOfCrapException should be be caught at the GUI level and no earlier.
Catching the exception and returning an error status is often not a bright idea. You clutter client code with error checking, and nine times out of ten the error status won't be checked in the first place - both serious issues that structured exception handling is trying to solve.
Sometimes you can start to suffer from exception bloat. There is an overly long list of possible exceptions, or maybe you don't even know up front what exceptions may be thrown. Many people decorate their methods with a meaningless and useless "throws Exception". Bad move. There are a couple of ways to go about this. The first is to make more use of custom exceptions, structured as a sensible class hierarchy, so that a simple "throws BaseClassException" can stand for a whole host of different SubClassExceptions. Alternatively, you may decide to catch some or all exceptions, wrap them inside a single generic exception, and throw that. For illustrations of both techniques, see e.g. java.rmi.RemoteException.
Catching a RuntimeException is usually bad practice. They represent an error which should not happen at all and indicate that there is something seriously wrong with the assumptions of the surrounding code. Sure, you will want to catch them eventually so that the application keeps on running, but you will want to do so at a very coarse-grained, high level, well outside the bad patch of code.
None of these rules are hard and fast. Recently, when working with a controller servlet expecting a fair number of parameters, I wondered if I should clutter up my code with null tests. Instead, I decided that only a user typing in the controller URL could reasonably cause this to happen and decided to catch the NullPointerException and redirect the user to the appropriate starting page. I'm still not sure whether that was the best thing to do or not, but it looks clean.
- Peter

[This message has been edited by Peter den Haan (edited May 11, 2001).]
 
Ganapathi Srinivasan
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Peter and David,
That was indeed an exhaustive and clear explanations regarding exceptions in Java...
For a person like me who started off with VB, exceptions in Java were indeed a bit difficult to grasp at the beginning. But now, things are indeed smooth...
Still I feel that something can be done in Java with respect to Exceptions...I may be wrong...still I feel that Java should do something as to give customized error codesfor every exception(something like in VB)instead of throwing the same Exception object (like tennis balls...). For example, inspite of any error in Database, we get only a (dumb)SQLException object. Java can try to give the error code like..if is error #78757 then it means "Database Deleted"(jus kidding..) or something like that...
That would indeed reduce the amount of debugging Java develepors have to endure!!
Any follow ups??
Regards,
Ganp.
 
Peter den Haan
author
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Originally posted by Ganapathi Raman:
[...] still I feel that Java should do something as to give customized error codesfor every exception(something like in VB)instead of throwing the same Exception object (like tennis balls...). For example, inspite of any error in Database, we get only a (dumb)SQLException object. Java can try to give the error code like..if is error #78757 then it means "Database Deleted"(jus kidding..) or something like that...


Error codes... <shudder>. Ever received "ORA-9239572312781: Twixor Lock Marooned In Tablespace", to be followed by a frantic search through interminable error listings to find out what the *&!% is wrong this time?
Coming to talk about SQLException, that's quite an exceptional exception in that it is just a generic way to reflect the errors coming from the database. It wraps a database error code the way java.rmi.ServerException wraps a server-side exception. See SQLException.getErrorCode(). You must be happy now
Likewise, nothing stops you from implementing your own Exception class with an error code. Myself, I'm not convinced. They cannot express relationships the way an exception hierarchy can, or carry extra information particular to a single kind of problem.
- Peter

[This message has been edited by Peter den Haan (edited May 11, 2001).]
 
Talk sense to a fool and he calls you foolish. -Euripides A foolish tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
    Bookmark Topic Watch Topic
  • New Topic