try catch statement

L

lowenbrau

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
 
P

Patricia Shanahan

lowenbrau said:
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

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
 
L

Lew

lowenbrau said:
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
}
}

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.
 
C

Christopher Benson-Manica

[comp.lang.java.programmer] lowenbrau said:
[-- 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.)
 
D

Daniel Pitts

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

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.
 
T

Thomas Hawtin

Daniel said:
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
 
T

Twisted

[comp.lang.java.programmer] lowenbrau said:
[-- 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. :)
 
R

Roedy Green

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.
 
R

Roedy Green

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.
 
S

Stefan Ram

Roedy Green said:
final int x;
if ( a > 0 )
{ x =14; }
else if ( a < 0 )
{ x = 0;}
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;
 
T

Twisted

or

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.
 
P

Patricia Shanahan

Stefan said:
Roedy Green said:
final int x;
if ( a > 0 )
{ x =14; }
else if ( a < 0 )
{ x = 0;}
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;

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
 
T

Thomas Hawtin

Patricia said:
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
 
C

Christopher Benson-Manica

[comp.lang.java.programmer] Roedy Green said:
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 )
{ x =14; }
else if ( a < 0 )
{ x = 0;}
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.
 
C

Christopher Benson-Manica

[comp.lang.java.programmer] Roedy Green said:
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 )
{ x =14; }
else if ( a < 0 )
{ x = 0;}
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.
 
C

Christopher Benson-Manica

[comp.lang.java.programmer] Stefan Ram said:
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!
 
R

Roedy Green

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.
 
R

Roedy Green

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;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top