使用if语句处理错误

时间:2014-10-12 13:12:09

标签: java

这是为了验证我的GUI输入并确保用户无法输入超出范围的值

我正在尝试使用if语句处理此异常,但我仍然在打印红色错误消息。我只想打印“超出范围”的消息。我不想在我的控制台中出现这些红色异常错误。请帮忙或建议。处理这种情况的任何其他方式都可以。

    if (totalTimeToTakeOff <= 0 || totalTimeToLand <= 0 || arrivalRate < 0
                    || arrivalRate > 1 || departureRate < 0 || departureRate > 1
                    || remaingFuel <= 0 || numOfRunways <= 0 || sIMULATION_TIME < 0) {
                throw new IllegalArgumentException("Values out of range");

            }

4 个答案:

答案 0 :(得分:1)

你在这里做的是创建一个新的IllegalArgumentException对象,然后此方法抛出此异常。抛出异常时,调用此方法的代码部分必须处理该异常,或者打印那些“红线”(基本上是堆栈跟踪)。因此,举一个简单的例子,假设你有方法divide()

public double divide(double a, double b){
    if(b==0){
       throw new IllegalArgumentException("Divisor cannot be 0");
    }
    return a/b;
}

现在,当代码的其他部分调用此方法时,您可以选择处理此方法抛出的IllegalArgumentException。

 try{
     double c = divide(a,b);
 }catch(IllegalArgumentException e){
    //put whatever code you want here
 }

如果没有捕获异常,那么代码会中断并打印出堆栈跟踪(红色文本)。换句话说,您的代码按预期运行;在某些情况下,该部分代码会抛出IllegalArgumentException,并且调用该方法的代码不会捕获异常并处理它(例如通过打印出有关异常的消息)。

另外,只是一个小问题 - java中的错误与异常不同。错误表示程序无法恢复的进程,并且无法捕获错误。可以捕获异常(所有继承Exception类的类)。可以检查或取消选中异常 - 必须通过catch语句捕获已检查的异常,而未检查的异常则不会。已检查异常的示例是IOException,而未经检查的异常的示例是您在此处显示的IllegalArgumentException。

还有一件事 - 例外意味着代码中的异常。如果抛出这个IllegalArgumentException,比如一个类构造函数或一个可以用于许多一般目的的方法,那么抛出它是有意义的。但是,如果该方法仅存在 以检查输入是否有效,那么让它返回一个布尔值(true或false)而不是抛出异常。

另一个原因是,与简单地返回true或false相比,异常处理往往相当缓慢。

答案 1 :(得分:1)

您需要了解this,请仔细研究。

基本理解是

try { 
   //Something that can throw an exception.
} catch (Exception e) {
  // To do whatever when the exception is caught.
} 

还有一个finally块,即使出现错误也始终执行。它像这样使用

try { 
   //Something that can throw an exception.
} catch (Exception e) {
  // To do whatever when the exception is caught & the returned.
} finally {
  // This will always execute if there is an exception or no exception.
}

InputMismatchException - 如果下一个标记与Integer正则表达式不匹配,或者超出范围 NoSuchElementException - 如果输入用尽 IllegalStateException - 如果此扫描程序已关闭

所以你需要捕捉像

这样的例外
try { 
   rows=scan.nextInt();
} catch (InputMismatchException e) {
  // When the InputMismatchException is caught.
  System.out.println("The next token does not match the Integer regular expression, or is out of range");
} catch (NoSuchElementException e) {
  // When the NoSuchElementException is caught.
  System.out.println("Input is exhausted");
} catch (IllegalStateException e) {
  // When the IllegalStateException is caught.
  System.out.println("Scanner is close");
} 

答案 2 :(得分:0)

您可以检查值而不会抛出异常

if (!checkValues())
    System.out.println("Values out of range");

答案 3 :(得分:0)

你可以打印到控制台并退出Java(而不是抛出异常),因为这实际上就是Exception所做的。

System.out.println("Values out of range");
System.exit(0);

或者,在调用方法时捕获异常

try{
    if(checkValues())
    ...
}catch(Exception e){
    System.out.println("Values out of range");
}