Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / August 2007

Tip: Looking for answers? Try searching our database.

try catch statement

Thread view: 
lowenbrau - 15 Aug 2007 13:19 GMT
Hi,

do you declare variables outside or inside a try catch statement?

for example:

public void nameitmethod()
{
   String str = null; //HERE?
   try
   {
       String str = null; // OR HERE?
       //do something
   }
   catch (Exception e)
   {
      //do something
   }
}

ST
Patricia Shanahan - 15 Aug 2007 13:36 GMT
> Hi,
>
[quoted text clipped - 17 lines]
>
> ST

The usual rule I follow is to declare variables with the minimum scope
that they need. If all uses of str are inside the try block, the
declaration of str would also be inside. If I need str in the catch
block, or in later code, its declaration has to go outside.

Patricia
Daniel Pitts - 15 Aug 2007 16:30 GMT
> > Hi,
>
[quoted text clipped - 24 lines]
>
> Patricia

I'll accept your bid and raise you...

I go to some length at times to shorten my scope.  If there are
statements after the catch block that can be moved inside the try
block, and moving those statements would allow me to move my variable
declaration into the try block as well, I will often do that.

I usually prefer all my local variables to be "final" if possible, so
the common idiom of init to null, try to set, catch, check if null
bothers me.  Although, I know at certain times its unavoidable.
Thomas Hawtin - 15 Aug 2007 16:51 GMT
> I go to some length at times to shorten my scope.  If there are
> statements after the catch block that can be moved inside the try
> block, and moving those statements would allow me to move my variable
> declaration into the try block as well, I will often do that.

OTOH, it's also good to reduce the scope of the try block.

> I usually prefer all my local variables to be "final" if possible, so
> the common idiom of init to null, try to set, catch, check if null
> bothers me.  Although, I know at certain times its unavoidable.

I like single assignment of variables (even if I don't always clutter
with final), I don't like nulls and I certainly don't like pointless
conditional statements. However, you can usually get around the problem
by separating the try-catch and try-finally.

Tom Hawtin
Roedy Green - 16 Aug 2007 02:33 GMT
On Wed, 15 Aug 2007 15:30:31 -0000, Daniel Pitts
<googlegroupie@coloraura.com> wrote, quoted or indirectly quoted
someone who said :

>I usually prefer all my local variables to be "final" if possible, so
>the common idiom of init to null, try to set, catch, check if null
>bothers me.  Although, I know at certain times its unavoidable.

I have got in the habit of putting final on every variable, and
removing it if it turns out the variable is not really final.  The
NON-finals are the weird ones, and relatively rare.

It is nice to have that fact documented.

The other idiom I often use looks like this:

final int x;
if ( a > 0 )
 { x =14; }
else if ( a < 0 )
 { x = 0;}
else
  { x = 7;}

It makes sure you assign x once and only once.
Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Roedy Green - 16 Aug 2007 02:40 GMT
>I have got in the habit of putting final on every variable, and
>removing it if it turns out the variable is not really final.  The
>NON-finals are the weird ones, and relatively rare.
I have written a hymn of praise to final at
http://mindprod.com/jgloss/final.html
Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Stefan Ram - 16 Aug 2007 03:00 GMT
>final int x;
>if ( a > 0 )
[quoted text clipped - 3 lines]
>else
>   { x = 7;}

 or

final int x = a > 0 ? 14 : a < 0 ? 0 : 7;

 or

final int x = new int[]{ 0, 7, 14 }[ Integer.signum( a )+ 1 ];

 or

final int x =( Integer.signum( a )+ 1 )* 7;
Lew - 16 Aug 2007 04:27 GMT
> final int x =( Integer.signum( a )+ 1 )* 7;

You have an amazing gift for patterns.  Kudos.

Signature

Lew

Twisted - 16 Aug 2007 07:30 GMT
> >final int x;
> >if ( a > 0 )
[quoted text clipped - 7 lines]
>
> final int x = a > 0 ? 14 : a < 0 ? 0 : 7;

Excellent, though I'd parenthesize the inner conditional and turn the
magic numbers into named constants.

>   or
>
> final int x = new int[]{ 0, 7, 14 }[ Integer.signum( a )+ 1 ];

Yuck. Litters the heap with temporary objects and can throw. Make the
array static final, also to get rid of anonymous magic numbers, but
see below.

>   or
>
> final int x =( Integer.signum( a )+ 1 )* 7;

Calls a method. Clearest if this pattern is intended and best if
performance is not an issue, and otherwise crummy. And replace that
literal 7 with a named constant!

At least this one neither gratuitously creates and discards a compile-
time-constant object nor can throw OOME, incur a bounds-check
overhead, or similarly.
Patricia Shanahan - 16 Aug 2007 14:40 GMT
>> final int x;
>> if ( a > 0 )
[quoted text clipped - 15 lines]
>
> final int x =( Integer.signum( a )+ 1 )* 7;

What criteria would people use to choose between these four methods?

Personally, I like Roedy's version because it is so very simple and
clear. Anyone reading it is going to know what is going on immediately.

The second is OK, but I would rather see it with parentheses and it
still does not lay out as clearly as the first one exactly what is
happening. I tend to think of ?: as a poor man's if-then-else, suitable
for use in C macros where expressions are permitted but statements are not.

The third and fourth are a bit too clever for my taste. Yes, they do the
right thing, but I have to stop and think to see it. I don't want to
spend my thinking time on something that could have been made totally
obvious.

Patricia
Thomas Hawtin - 16 Aug 2007 16:50 GMT
> The second is OK, but I would rather see it with parentheses and it
> still does not lay out as clearly as the first one exactly what is
> happening. I tend to think of ?: as a poor man's if-then-else, suitable
> for use in C macros where expressions are permitted but statements are not.

Well, you can lay it out clearly. IMO, more clear than the cluttered
if/else-if/else form.

        final int x =
            (a<0) ?  0 :
            (a>0) ? 14 :
                     7;

Tom Hawtin
Roedy Green - 22 Aug 2007 12:11 GMT
>Personally, I like Roedy's version because it is so very simple and
>clear. Anyone reading it is going to know what is going on immediately.

My version was intended purely to show a simple pattern of using final
without an assignment then multiple assignments.  It has the nice
feature that the compiler warns you if  you forget to assign in some
situation or assign twice in some situation.

You can use the same pattern with a switch or complex if else nests.
Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Christopher Benson-Manica - 16 Aug 2007 21:22 GMT
> final int x = a > 0 ? 14 : a < 0 ? 0 : 7;

Admirably terse, but the prize purse for terseness has been steadily
decreasing.  Unless you're coding everything from an 80x24 terminal,
a couple of extra lines of screen real estate are well worth the vast
improvement in readability.

> final int x = new int[]{ 0, 7, 14 }[ Integer.signum( a )+ 1 ];

Either this is tongue-in-cheek or deviously evil...

> final int x =( Integer.signum( a )+ 1 )* 7;

Ditto!

Signature

 C. Benson Manica    | I appreciate all corrections, polite or otherwise.
cbmanica(at)gmail.com |
----------------------| I do not currently read any posts posted through
  sdf.lonestar.org   | Google groups, due to rampant unchecked spam.

Christopher Benson-Manica - 16 Aug 2007 19:43 GMT
> I have got in the habit of putting final on every variable, and
> removing it if it turns out the variable is not really final.

It's a good habit IMO, and the developers of IntelliJ agree with you.

> final int x;
> if ( a > 0 )
[quoted text clipped - 3 lines]
> else
>   { x = 7;}

> It makes sure you assign x once and only once.

I like the idiom, but I have to say that the formatting looks highly
idiosyncratic to me.

Signature

 C. Benson Manica    | I appreciate all corrections, polite or otherwise.
cbmanica(at)gmail.com |
----------------------| I do not currently read any posts posted through
  sdf.lonestar.org   | Google groups, due to rampant unchecked spam.

Roedy Green - 22 Aug 2007 12:14 GMT
On Thu, 16 Aug 2007 18:43:10 +0000 (UTC), Christopher Benson-Manica
<ataru@faeroes.freeshell.org> wrote, quoted or indirectly quoted
someone who said :

>> final int x;
>> if ( a > 0 )
[quoted text clipped - 8 lines]
>I like the idiom, but I have to say that the formatting looks highly
>idiosyncratic to me.

The odd formatting was just to make it more compact.  In my actual
code, IntelliJ reformat is in complete control of the layout.  It
would look more like this:

final int x;
if ( a > 0 )
   {
   x =14;
   }
else if ( a < 0 )
   {
   x = 0;
   }
else
   {
   x = 7;
   }
Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Wojtek - 22 Aug 2007 16:37 GMT
Roedy Green wrote :
> On Thu, 16 Aug 2007 18:43:10 +0000 (UTC), Christopher Benson-Manica
> <ataru@faeroes.freeshell.org> wrote, quoted or indirectly quoted
[quoted text clipped - 30 lines]
>     x = 7;
>     }

Or you could do this:

final int x = ( a > 0 ) ? 14 : ( a < 0 ) ? 0 : 7;

Signature

Wojtek :-)

Christopher Benson-Manica - 16 Aug 2007 21:16 GMT
> I have got in the habit of putting final on every variable,

One of the (many) things I like a lot about IntelliJ is that it will
helpfully suggest this very thing.

> final int x;
> if ( a > 0 )
[quoted text clipped - 3 lines]
> else
>   { x = 7;}

> It makes sure you assign x once and only once.

I like that, but I find the format (specifically the placement of the
braces) to be rather odd.

Signature

 C. Benson Manica    | I appreciate all corrections, polite or otherwise.
cbmanica(at)gmail.com |
----------------------| I do not currently read any posts posted through
  sdf.lonestar.org   | Google groups, due to rampant unchecked spam.

Lew - 15 Aug 2007 13:45 GMT
> Hi,
>  
[quoted text clipped - 15 lines]
>     }
> }

Yes, I declare variables outside or inside a try-catch block, or indeed, any
block.  (You want in this matter to speak of a "block", not a "statement".  A
block is a set of statements delineated by curly braces.
<http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.2>
<http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.5>
)

The key word is "scope".  Scope is how far the meaning of a variable extends.
  For practical purposes, a variable has meaning from its point of
declaration to the closing curly brace that follows it.  (There are nuances
that I ignore here.  They are precisely defined by
<http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.4.2>
.)

In your example, the first declaration of "str" has meaning until the closing
brace of the method.  That means that every subsequent line of code inside the
method, including inside the try{} and catch{} blocks, can use that variable.

However, inside the try{} block there's a declaration of another variable
"str".  According to
<http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.3.1>
this variable "shadows" the outer-scoped str within its inner scope.  The
scope of the inner str is the rest of the try{} block.

Inside the catch{} block, the try{}-scoped str is inaccessible, so str is the
method-scoped variable.

Signature

Lew

Christopher Benson-Manica - 15 Aug 2007 14:24 GMT
> [-- text/plain, encoding quoted-printable, charset: iso-8859-1, 21 lines --]

Please don't post multipart messages to Usenet.

> do you declare variables outside or inside a try catch statement?

Inside if possible.  (Ditto what Patricia said.)

Signature

 C. Benson Manica    | I appreciate all corrections, polite or otherwise.
cbmanica(at)gmail.com |
----------------------| I do not currently read any posts posted through
  sdf.lonestar.org   | Google groups, due to rampant unchecked spam.

Twisted - 15 Aug 2007 21:57 GMT
On Aug 15, 9:24 am, Christopher Benson-Manica
<at...@faeroes.freeshell.org> wrote:
> > [-- text/plain, encoding quoted-printable, charset: iso-8859-1, 21 lines --]
>
> Please don't post multipart messages to Usenet.

To text/discussion groups specifically. Binaries groups certainly
permit binaries. Of course nowhere is HTML or Quoted-Printable
welcome. :)
Roedy Green - 22 Aug 2007 12:16 GMT
>To text/discussion groups specifically. Binaries groups certainly
>permit binaries. Of course nowhere is HTML or Quoted-Printable
>welcome. :)

That's why perhaps HTML-based forums are taking over from newsgroups.
Many times I wished I could use HTML or a image to explain something
in Java.  On my website, I have the freedom to use both.

Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Roedy Green - 16 Aug 2007 00:34 GMT
>do you declare variables outside or inside a try catch statement?
if you decleare variables  outside the block, they will be available
outside the block.  If you need them only inside the block, declare
them there, same as any other block.
Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.