Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is an "Exception-controlled" loop?

I'm trying to do a question on my study guide that asks:

Write an exception-controlled loop that loops until the user enters an integer between 1 and 5.

I can't decipher what this question really means since I've never heard of that term before, but this is my best guess:

    Scanner input = new Scanner(System.in);
    int a = 0;

    while(a <= 0 || a > 5)
    {
        try {
            a = input.nextInt();

            if(a <= 0 || a > 5)
                throw new OutOfRangeException(); //my own Excpt. class
        } catch (OutOfRangeException e) {
            System.out.println(e.getMessage());
        }
    }

What do you you guys think? Am I missing something here?

like image 349
LTH Avatar asked Dec 13 '22 07:12

LTH


2 Answers

I think that your catch clause should be outside the loop

 Scanner input = new Scanner(System.in);
 int a = 0;
 try
 {
    while(true)
    {       
        a = input.nextInt();
        if(a <= 0 || a > 5)
            throw new OutOfRangeException(); //my own Excpt. class
    } 
 }
 catch (OutOfRangeException e) {
    System.out.println(e.getMessage());
 }

I haven't actually heard the term "exception controlled loop", but I think it means that it's an infinite loop that exits upon exception. Seems logical.

As the comments say, if you need to loop until the user enters a number between 1 and 5, the condition to throw should be

 if(a >= 1 && a <= 5)
like image 153
Armen Tsirunyan Avatar answered Dec 30 '22 22:12

Armen Tsirunyan


"Exception-controlled" is not a standard term, and anyway, using exceptions for control flow is a well-known bad practice. But to demonstrate it most clearly (i.e. badly), I would leave out the loop check and just write while(true) so that the loop is obviously only controlled by the exception.

like image 44
Kilian Foth Avatar answered Dec 30 '22 21:12

Kilian Foth