简体   繁体   English

我在Java中抛出的异常无法正常工作

[英]My thrown exceptions in Java aren't working

I'm working on a project where we are to create a cash register system that gives errors for orders of $0.00 and 0 total items. 我正在做一个项目,我们将在该项目中创建一个收银机系统,该系统将给订单$ 0.00和0个总项目带来错误。 The code for the exceptions is below. 异常代码如下。 I have to use this method. 我必须使用这种方法。

  public boolean ValidateOrderTotal(double total)  
  {
      boolean validTotalFlag = true;
      try
      {
          if (total < 0)
          Exception invalidTotalEX = new Exception ("Total mst be >= $0.00");
          throw invalidTotalEX;
      }
  catch (Exception invalidTotalEX)(
  validTotalFlag = false;
  SetTotal(0.00);
  System.out.println(invalidTotalEX);
  }

return validTotalFlag;

public boolean ValidateOrderProductTotal (double totalItems)
{
boolean validProdctTotalFlag = true;
try
{
if (totalItems < 0)
(Exception invalidProductTotalEX = new Exception ("Product total must be >=0");
throw invalidProductTotalEX;
}
}
catch (Exception invalidProductTotalEX)(
validProdctTotalFlag = false);
SettotalItems (0);
system.out.println (invalidProductTotalEX);
)
return valid ProductTotalFlag
      if (total < 0)
      Exception invalidTotalEX = new Exception ("Total mst be >= $0.00");
      throw invalidTotalEX;

needs curly braces 需要花括号

      if (total < 0) {
          Exception invalidTotalEX = new Exception ("Total mst be >= $0.00");
          throw invalidTotalEX;
      }

You have a second if with the exact same issue. 如果有完全相同的问题,请稍等。

Also your catch blocks need to use { and } around the statements. 另外,您的catch块还需要在语句周围使用{} You are using ( and ) in some places. 您在某些地方使用()

As it throws error when it is 0 it should be: 当它为0时会引发错误,因此应该为:

if (total <= 0) {
          Exception invalidTotalEX = new Exception ("Total mst be > $0.00");
          throw invalidTotalEX;
      }

"catch (Exception invalidTotalEX)(" - there should be last '{' after "catch (Exception invalidTotalEX)(" instead of '(' “ catch(Exception invalidTotalEX)(”-“ catch(Exception invalidTotalEX)(”之后应该有最后一个'{',而不是'('

Variable name does not matter, for example: 变量名称无关紧要,例如:

viktor@Viks-pro:~/tmp/test $ cat ExTest.java
import java.util.*;
public class ExTest
{   public static void main(String[] args)
    {   try
        {   throw new Exception("Something should be different");
        }
        catch(Exception e)
        {   System.out.println("Exception: "+e.getMessage());
        }
    }
}viktor@Viks-pro:~/tmp/test $ java ExTest
Exception: Something should be different

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM