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 / February 2006

Tip: Looking for answers? Try searching our database.

while(true) { try{ ... } catch(Exception e) { ... }  }

Thread view: 
imanhp@gmail.com - 05 Feb 2006 23:00 GMT
Hi.

I have a small problem here with my try/catch inside a while loop.
Im doing a quick and dirty forced read like so:

-----------------------------------------------------------------
       Scanner inp = new Scanner(System.in);
       PrintStream out = System.out;
       double num = 0;

       while(true) {
           try { num = inp.nextDouble(); return num; }
           catch(Exception e) { out.println("reenter value: "); }
       }
------------------------------------------------------------------

The problem is that try clause wont be tried again in the while loop
if a enter a non numeric input the first time.

As if the exception cant be ignored for some reason.
The code will just wind up printing "reenter value: " forever.

Why is this and how do i fix it?

cheers
//iman
Claudio Nieder - 05 Feb 2006 23:55 GMT
Hi,

> As if the exception cant be ignored for some reason.
> The code will just wind up printing "reenter value: " forever.
>
> Why is this and how do i fix it?

The why seems obvious to me, nextDouble() sees a non number so throws an
exception and stays where it is. When the while reenters it sees the same
non-number and throws again the exception etc.

The fix I do not know, never having used the Scanner class.

You have to somehow make it all start again on the next input.

claudio
Signature

Claudio Nieder, Kanalweg 1, CH-8610 Uster, Tel +41 79 357 6743
yahoo messenger: claudionieder aim: claudionieder icq:42315212
mailto:private@claudio.ch                http://www.claudio.ch

Roedy Green - 06 Feb 2006 00:43 GMT
>  while(true) {
>            try { num = inp.nextDouble(); return num; }

this does not make any sense. Why bother with the loop? The first time
through you exit the method.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

JScoobyCed - 06 Feb 2006 05:36 GMT
>> while(true) {
>>           try { num = inp.nextDouble(); return num; }
>
> this does not make any sense. Why bother with the loop? The first time
> through you exit the method.

Somehow it does make sense. I guess imanhp wants to loop until a decimal
value is entered. If the user enters a decimal at the first time, then
you exit the loop.

A quick fix to the initial code:
<code>
Scanner inp = null;
PrintStream out = System.out;
double num = 0;
while(true) {
 inp = new Scanner(System.in);
 try {
  num = inp.nextDouble();
  return num;
  }
 catch(Exception e) { out.println("reenter value: "); }
}
</code>

Signature

JSC

Ranganath Kini - 06 Feb 2006 07:03 GMT
Hi,

Have a look at this code:

public class TryNumberParse {
   public static void main( String[] args ) {
       double num = 0.0;

       while( true ) {
           try {
               System.out.print( "Enter a value: " );
               System.out.println( "The value entered was: " + ( num =
getNum() ) );
           } catch( Exception e ) {
               System.out.println( "Invalid value, please re-enter...
" );
               continue;
           }
       }
   }

   private static double getNum() {
       Scanner inp = new Scanner( System.in );
       return inp.nextDouble();
   }
}

Hope it helps!
zero - 06 Feb 2006 12:40 GMT
imanhp@gmail.com wrote in news:1139180450.334075.96290
@g44g2000cwa.googlegroups.com:

>         Scanner inp = new Scanner(System.in);
>         PrintStream out = System.out;
[quoted text clipped - 4 lines]
>             catch(Exception e) { out.println("reenter value: "); }
>         }

A loop with an always-true condition is usually a *very* bad idea.  Only
experienced programmers should ever do this, and only with a very good
reason.

You should also try to avoid using exceptions for common problems, such
as this input problem.  The Scanner class provides methods to avoid
exactly this.

Here is some improved code, with a lot of comments to help you
understand why it is better:

Scanner inp = new Scanner( System.in );
// ask for the first value
System.out.print("enter value: ");
// as long as the user doesn't enter a double
// this is much more intuitive than "as long
// as true is true", as the original code said
while(!inp.hasNextDouble())
{
  // ask to re-enter the value
  System.out.print("re-enter value: ");
  // skip the incorrect value
  inp.next();
}
// inp.hasNextDouble returned true, so we are
// sure that there is a double value in the
// Scanner - no need for exceptions
Double d = inp.nextDouble();
System.out.println("value entered: " + d);
Monique Y. Mudama - 06 Feb 2006 20:20 GMT
> imanhp@gmail.com wrote in news:1139180450.334075.96290
> @g44g2000cwa.googlegroups.com:
[quoted text clipped - 15 lines]
> as this input problem.  The Scanner class provides methods to avoid
> exactly this.

Aren't try/catch blocks also fairly expensive?  Putting one inside a
while loop seems like a bad habit.  Granted, in this particular case,
the intention is for the loop to iterate very few times, and the loop
is also dependent on user input, which will in any case be much slower
than whatever code is being processed.

Still, it seems like something to avoid, much like always-true loops.

Signature

monique

Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html

zero - 06 Feb 2006 20:56 GMT
> Aren't try/catch blocks also fairly expensive?

Yep, that's one of the main reasons to use alternatives when they are
available.  The program flow with try/catch blocks is very complex - even
more so if there's a finally block - and require a lot of internal
computations.

Which does not mean you have to stay away from exceptions altogether.  
Structured exception handling is a very good thing, as long as it is used
for what it was envisioned to do: handle exceptional situations, not
situations that happen in normal program flow.  Incorrect user input falls
under the normal category.
Thomas Hawtin - 06 Feb 2006 21:21 GMT
>> A loop with an always-true condition is usually a *very* bad idea.  Only
>> experienced programmers should ever do this, and only with a very good
>> reason.

Unless you are of the Single Entry Single Exit (SESE) persuasion, using
a break or return to exit a loop seems reasonable. Using an auxiliary
boolean variable complicates matters. Duplicating conditions is
repeating yourself (keep it DRY).

> Aren't try/catch blocks also fairly expensive?  Putting one inside a
> while loop seems like a bad habit.  Granted, in this particular case,
> the intention is for the loop to iterate very few times, and the loop
> is also dependent on user input, which will in any case be much slower
> than whatever code is being processed.

Not really.

Creating exceptions is excessively expensive. Throwing exceptions is
moderately expensive.

Remember that a synchronised block is effectively a try/finally. We have
known synchronisation (in normal circumstances) isn't expensive for
years. Perhaps you the worst thing you can say about try blocks in
relation to performance is that they may prevent inlining on some JVMs.

Tom Hawtin
Signature

Unemployed English Java programmer
http://jroller.com/page/tackline/

Monique Y. Mudama - 07 Feb 2006 20:19 GMT
> Unless you are of the Single Entry Single Exit (SESE) persuasion,
> using a break or return to exit a loop seems reasonable. Using an
> auxiliary boolean variable complicates matters. Duplicating
> conditions is repeating yourself (keep it DRY).

What does DRY mean?

Signature

monique

Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html

Thomas Hawtin - 07 Feb 2006 22:20 GMT
>> Unless you are of the Single Entry Single Exit (SESE) persuasion,
>> using a break or return to exit a loop seems reasonable. Using an
>> auxiliary boolean variable complicates matters. Duplicating
>> conditions is repeating yourself (keep it DRY).
>
> What does DRY mean?

Don't Repeat Yourself.

"DRY says that every piece of system knowledge should have one
authoritative, unambiguous representation. Every piece of knowledge in
the development of something should have a single representation. A
system's knowledge is far broader than just its code. It refers to
database schemas, test plans, the build system, even documentation."
  -- http://www.artima.com/intv/dryP.html

In this narrow case, the little piece of system knowledge was when to
exit the loop.

Tom Hawtin
Signature

Unemployed English Java programmer
http://jroller.com/page/tackline/

Monique Y. Mudama - 07 Feb 2006 23:32 GMT
>> What does DRY mean?
>
[quoted text clipped - 9 lines]
> In this narrow case, the little piece of system knowledge was when
> to exit the loop.

Ah.  Thank you.  I hadn't heard of the acronym, but I agree with the
sentiment!

Signature

monique

Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html

Chris Uppal - 07 Feb 2006 08:28 GMT
> Aren't try/catch blocks also fairly expensive?

No.  It's implementation-dependent but there is no reason (given any reasonable
implementation technology) why it should have /any/ direct time cost at all.

The indirect costs may be non-zero.  For instance a try/catch might interfere
with optimisation in the JIT (if any).  The records required to implement
zero-cost try/catch take up some space, and hence some (tiny) time too. But I
doubt if such effects are worth worrying about in most cases.

Actually throwing/catching an exception is, naturally, a different kettle of
fish entirely.

   -- chris
Dimitri Maziuk - 06 Feb 2006 20:53 GMT
zero sez:
> imanhp@gmail.com wrote in news:1139180450.334075.96290
> @g44g2000cwa.googlegroups.com:
[quoted text clipped - 11 lines]
> experienced programmers should ever do this, and only with a very good
> reason.

And reading user input tends to be one of them. Typical scenario
is when you want to give them a limited number of tries (loop
with a counter: for), validate the input (post-condition loop:
do .. while), *and* let them hit Esc and abort the whole thing
(break/exit in the middle). It doesn't really fit into any of
the proper structured programming constructs, so you might as
well go for while(1).

Dima
Signature

We're part of that admittedly-too-small group that is trying to save the
human race from itself. With any luck, we'll fail abjectly and the
cockroaches will win out.
                                                  -- Mike Andrews



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



©2009 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.