【问题标题】:Continue program after exception异常后继续程序
【发布时间】:2017-03-13 23:18:26
【问题描述】:

好的,到目前为止我有这个:

import java.util.Random;
import java.util.Scanner;
class TooHighException extends Exception {}

class TooLowException extends Exception {}

class CorrectException extends Exception {}

public class HighLow {     
    public static void main(String[] args) throws TooLowException, TooHighException, CorrectException {

        Random random = new Random();
        Scanner scanner = new Scanner(System.in);
        int number = random.nextInt(100);
        int guess = -1;
        while (guess != number) {
            System.out.print("Enter your guess: ");
            guess = scanner.nextInt();
            if (guess < number) {
                throw new TooLowException();
            } else if (guess > number) {
                throw new TooHighException();
            } else {
                throw new CorrectException();
            }
        }
    }
}

应该发生的是程序选择一个随机数,并提示用户猜测该数字。然后它会说明猜测是否太高、太低或正确。我知道Exceptions 不应该以这种方式使用,但这是要求的。问题是当我抛出Exception 时,它不允许我输入新的猜测。有什么帮助吗?

【问题讨论】:

  • 你需要尝试/捕捉。
  • 你能给我举个例子来说明你的意思吗?不要求你为我编码。这是我运行它并猜测时得到的结果:输入您的猜测:线程“main”java.lang.UnsupportedOperationException 中的 99 异常:尚不支持。在 TooHighException.(HighLow.java:8) 在 HighLow.main(HighLow.java:43) C:\Users\Roop\AppData\Local\NetBeans\Cache\8.1\executor-sn-ps\run.xml :53: Java 返回:1 BUILD FAILED(总时间:3 秒)

标签: java exception continue


【解决方案1】:

您正在使用throw 引发异常,但如果您想处理异常,您应该使用trycatch 块。请参阅此 answer 以了解不使用 trycatch 块时会发生什么。

在可能发生异常的地方使用try 块。

在您的代码中,它发生在 if-else if-else 块中。

所以,

while (guess != number) {
    System.out.print("Enter your guess: ");
    guess = scanner.nextInt();
    try {
        if (guess < number) {
            throw new TooLowException();
        } else if (guess > number) {
            throw new TooHighException();
        } else {
            throw new CorrectException();
        }
    } // end the try block
 }

现在您要处理异常而不是冒泡,因此您需要在 try 块之后立即使用 catch 块。

所以,

while (guess != number) {
    System.out.print("Enter your guess: ");
    guess = scanner.nextInt();
    try {
        if (guess < number) {
            throw new TooLowException();
        } else if (guess > number) {
            throw new TooHighException();
        } else {
            throw new CorrectException();
        }
    } catch(Exception e) {
         System.out.println(e);
    }
 }

当您使用您创建的Exceptions 时,最好提及异常是什么,就像引发异常时的原因一样。

为此,请覆盖 Exception 类的 toString()。如果您在代码中多次使用自定义异常类,则不必每次都在 catch 块中向用户写入消息。


编辑:

import java.util.Random;
import java.util.Scanner;
class TooHighException extends Exception {
}
class TooLowException extends Exception {
}
class CorrectException extends Exception {
}
public class HighLow {
     /**
     * @param args the command line arguments
     * @throws TooLowException
     * @throws TooHighException
     * @throws CorrectException
     */
    public static void main(String[] args) {
        Random random = new Random();
        Scanner scanner = new Scanner(System.in);
        int number = random.nextInt(100);
        int guess = -1;
        while (guess != number) {
            System.out.print("Enter your guess: ");
            guess = scanner.nextInt();
            try {
                if (guess < number) {
                    throw new TooLowException();
                } else if (guess > number) {
                    throw new TooHighException();
                } else {
                    throw new CorrectException();
                }
            } catch(Exception e) {
            System.out.println(e);
            }
        }
    } // end main
} // end class

【讨论】:

  • 当我尝试并猜测时,我得到以下信息:java.lang.UnsupportedOperationException: Not supported yet。我可以再猜一次,但它没有显示我的异常或告诉我它是太高还是太低
  • @Sroop 我已经编辑了您的代码并更新了答案。运行代码并告诉我。如果仍然抛出,则打印堆栈跟踪并编辑您的问题以包含堆栈跟踪。
  • @Sroop 当您自己处理异常时,您不必在main() 中使用throws。阅读我链接的答案以了解在哪里使用throws
【解决方案2】:

你最好检查一下 try/catch。

while(guess!=number){
try{
        System.out.print("Enter your guess: ");
           guess = scanner.nextInt();
           if (guess < number) {
               throw new TooLowException();
           } else if (guess > number) {
               throw new TooHighException();
           } else {
               throw new CorrectException();
           }
    }



   catch(TooLowException ex){
System.out.println("Too low.");   
}
catch(TooHighException ex){
System.out.println("Too high.");   
}
catch(CorrectException ex){
System.out.println("Correct.");   
}
   finally{
       //This block always executes.
   }
}

【讨论】:

    【解决方案3】:

    您应该考虑使用 try catch 块,而不是仅仅抛出异常。

    try { 
        //This block throws the exception.
    }
    Catch(Exception e) {
          //This block will run next.
    }    
    

    【讨论】:

      【解决方案4】:

      像这样?

      try {
          if (guess < number) {
              throw new TooLowException(); 
          } else if (guess > number) {
              throw new TooHighException(); 
          } else { 
              throw new CorrectException(); 
          }
      } catch (Exception e) {
          e.printStackTrace();
          continue;
      }  
      

      【讨论】:

        【解决方案5】:
        while (guess != number) {
            System.out.print("Enter your guess: ");
            guess = scanner.nextInt();
         try{ 
          if (guess < number) {
                throw new TooLowException();// when this line executes exception is thrown, anything written below this line will not run. If there is a catch block to catch this exception below try block, that will run next
            } else if (guess > number) {
                throw new TooHighException();
            } else {
                throw new CorrectException();
            }
         }
         catch(TooLowException e){
            //this will catch the exception you throw.
            //Usually we write e.printStacktrace() to get to know where the error occurred 
           // we also deallocate the allocated resources.
           //but in your case
           System.out.println("Too low");
        
         }
          catch(TooHighException e){
        
           System.out.println("Too high");
        
         }
          catch(CorrectException e){
        
           System.out.println("Correct");
        
         }
        }
        

        【讨论】:

        • 我想这差不多了,但是,它不再告诉用户它是太高还是太低。它只是允许另一个猜测。另外,我也应该看到异常,对吗?
        • 这是我在尝试时得到的结果:输入您的猜测:线程“main”java.lang.UnsupportedOperationException 中的 15 异常:尚不支持。在 TooLowException.(HighLow.java:22) 在 HighLow.main(HighLow.java:54) C:\Users\Roop\AppData\Local\NetBeans\Cache\8.1\executor-sn-ps\run.xml :53: Java 返回:1 BUILD FAILED(总时间:2 秒)
        • 你的类 TooLowException 扩展了异常吗?
        【解决方案6】:

        基本上你有以下问题。

        异常会终止程序执行,除非它们被 try catch 捕获(请参阅其他答案)。 因此,要继续,您需要捕获异常并打印一些内容以通知用户结果。 但是,如果您这样做,您可以简单地忽略异常并首先打印结果。

        【讨论】:

        • 这将是最简单的方法,但这不是教授想要的。事实上我是这样的,但她希望在例外情况下完成。
        • 好吧,在这种情况下,您应该已经拥有了所有需要的示例。
        猜你喜欢
        • 2020-11-14
        • 1970-01-01
        • 2015-10-31
        • 1970-01-01
        • 2021-06-20
        • 2014-12-18
        • 2021-05-13
        • 1970-01-01
        • 2013-11-11
        相关资源
        最近更新 更多