Java – what is an exception control loop?

I'm trying to ask a question in my study guide:

I can't decipher the true meaning of this question because I've never heard the word 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 think? Did I miss anything here?

Solution

I think 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 control loop", but I think it means that it is an infinite loop that exits when an exception occurs It seems logical

As the comment said, if you need to cycle until the user enters a number between 1 and 5, the condition thrown should be

if(a >= 1 && a <= 5)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>