# Stuck in continuous loop with try/catch block

• 02-02-2013, 02:01 AM
ndsmith20
Stuck in continuous loop with try/catch block
Hi, I need to create a try/catch blocks for the scanner class and be able to continue entering in more info after the exception is caught, here is what i have:
Circle Class
Code:

```public class Circle{                 String msg = "Radius of circle must be greater than 0";     private double radius;    // the radius of the circle     /**     * Constructor - Create a new circle.     *     * @param    inRadius  radius of the circle           *throw illegal argument exception if inRadius less than or equal to 0     */     public Circle(double inRadius ) {                 try                 {         if (inRadius <= 0.0)                   {                           throw new ShapeException(msg);                   }                 }                 catch(ShapeException e)                 {                                         }                   radius = inRadius;                       }     /**     * Return the radius of the circle.     *     * @return    radius of the circle     */     public double getRadius() {                 return radius;     }     /**     * set the radius     * @param newRadius                new radius of the circle           *throw exception if newRadius less than or equal to 0     */     public void setRadius(double newRadius) {                 try                 {         if (newRadius <= 0.0)                   {                           throw new ShapeException(msg);                   }                 }                 catch(ShapeException e)                 {                         System.out.println("Radius must be greater than 0");                         System.exit(0);                 }                 radius = newRadius;         }     /**     * Compute and return the area of the circle.     *     * @return    the area of the circle     */     public double area() {                 return Math.PI * radius * radius;     }     /**     * Stretches the size of the circle by multiplying     * the radius by the factor provided.     *     * @param    factor    factor to stretch by     *     */     public void stretchBy(double factor ) {         try                 {         if (factor <= 0.0)                   {                           throw new ShapeException(msg);                   }                 }                 catch(ShapeException e)                 {                         System.out.println("Factor must be greater than 0");                         System.exit(0);                 }                   radius = radius * factor;     }     /**     * Return a string representation of a circle.     *     * @return    a string representing this circle     */     public String toString() {       // implement body here                 return "Circle: "+radius;     } } // Circle```
Shape Exception Class
Code:

```public class ShapeException extends Exception {     public ShapeException(String message)   {       super(message);   } }```
Test Class
Code:

```import java.util.*; public class TestCircleC {   public static void main(String [] args) {                     String msg = "Shape Exception occured";           double radius = 0;           Scanner scan = new Scanner(System.in);           //System.out.print("Enter a circle radius: ");           boolean loop = true;         while(loop != false)         {         //System.out.print("Enter a circle radius: ");         try           {                   System.out.print("Enter a circle radius: ");                   radius =scan.nextDouble();                 // Instantiate a Circle object       Circle aCircle = new Circle(radius);                 // Print current status of the circle       System.out.println(aCircle);                   if(radius <= 0.0)                 {                         throw new ShapeException(msg);                 }           }           catch (ShapeException e)           {                   System.out.println("Shape Exception occured...");           }           catch(InputMismatchException e)           {                   System.out.println("InputMismatchException occurred...");           }           catch(NoSuchElementException e)           {                   System.out.println("CTRL+C Program stops...");                 loop = false;                 System.exit(0);                           }         }   } }```
My results:
Circle: 12.0
Circle: -12.0
Shape Exception occured...
InputMismatchException occurred...
Enter a circle radius: InputMismatchException occurred...
Enter a circle radius: InputMismatchException occurred...
Enter a circle radius: InputMismatchException occurred...
Enter a circle radius: InputMismatchException occurred.

• 02-02-2013, 03:43 AM
pbrockway2
Re: Stuck in continuous loop with try/catch block
Quote:

According to the API documentation nextDouble() "Scans the next token of the input as a double. This method will throw InputMismatchException if the next token cannot be translated into a valid double value. If the translation is successful, the scanner advances past the input that matched".

The important thing is that the method moves past the input that matched. If there is no input that matches (eg because the user entered "fo") then the scanner will not advance. So, in your case, the scanner sees "fo" and throws the exception, then another prompt is written and the scanner (which is still looking at "fo") will throw the exception again. And the whole process repeats itself for ever.

There is, therefore, a very important difference between nextDouble() and friends (nextInt() etc) and nextLine(). nextLine() always "consumes" its input and moves on to the next line while the others don't move at all if there is an exception.

This is a very common gotcha when people use Scanner for input and there are a couple of things you could explore to get the code to move on even when there is an exception:

(1) If you expect the value to be the only thing that the user enters before pushing the <enter> key, then you could use nextLine() rather than nextDouble(). This will return you a String rather than a double. You can get the corresponding double value by calling Double.parseDouble(). parseDouble() can also throw an exception (and will throw one if the string is "fo") which you could catch and report. But at least when you go round the loop the second time the scanner will return the next line of input the user enters and not keep seeing "fo" and throwing the exception.

(2) In the catch block for the InputMismatchException you could call the nextLine() method and do nothing at all with the String it returns. This will "consume" the string "fo" and anything that occurs on the line after it leaving you ready to receive more user input.

In terms of how much change is needed to your existing code (2) involves less work. There is also a hasNextDouble() method in the scanner class which tells you if there is a double ready to be read rather than your program finding out about it via an exception.
• 02-03-2013, 02:09 AM
ndsmith20
Re: Stuck in continuous loop with try/catch block
pbrock, I went with option 2 and it worked. Thank you so much!!!
• 02-03-2013, 02:26 AM
pbrockway2
Re: Stuck in continuous loop with try/catch block
You're welcome.