JAVA编写异常

时间:2014-11-28 07:43:03

标签: java exception

我应该编写例外来防止无效对象,例如字符串没有空格或者double和int数字在某个范围内。我真的很困惑如何做到这一点。我应该使用if / else语句吗?或者更多的try / catch语句?

编辑:需要验证每个对象。字符串不能有空格或只包含空格,数字不能小于零。还有其他五个try / catch语句,但我只包括一个。我的问题是我会写什么,以便异常输出对于不同的问题是不同的,有没有办法写它以避免为每个单独的try / catch编写每个异常?我查看了关于编写异常的其他帖子,但我还没有了解超级是什么或者做什么,不能使用它。

public class CD {
    String artistname = "";
    String albumname = "";
    double cdprice = 0;
    int amountinstock = 0;

    public CD(final String artistname, final String albumname, final double cdprice, final int amountinstock) {
        this.artistname = artistname;
        this.albumname = albumname;
        this.cdprice = cdprice;
        this.amountinstock = amountinstock;
    }

    public static void main(final String[] arg) throws Exception {

        try {
            final CD cd1 = new CD("Muse", "The Resistance", 11.99, 20);
            System.out.println(cd1.toString());
            System.out.println("=========================");
        } catch (final CDException cde) {
            System.out.println(cde.getMessage());
            System.out.println("=========================");
        }
    }
}

4 个答案:

答案 0 :(得分:1)

我会用if语句检查String,int,...如果出现错误,请抛出IllegalArgumentException

答案 1 :(得分:1)

首先,您必须编写检查输入是否无效的条件(即if语句)。当您检测到无效输入时,您应该抛出异常。

答案 2 :(得分:1)

您可以编写自定义异常,如提到的here

public class CustomException extends Exception {
    public CustomException(String message) {
        super(message);
    }
}

您可以为自定义异常提供一些逻辑名称,例如IntegerNumberOutofRangeException

然后你可以在你的代码中使用if else并为你提到的特定条件抛出自定义异常。

代码

int intNumber = 50;
if (intNumber > 60 && intNumber < 100) {
    // Do your work
} else {
    throw new CustomException("Integer number out of expected range of 60 to 100");
}

答案 3 :(得分:-1)

您应该使用IF进行验证。

最佳做法是不要从类的构造函数中抛出异常。 另一个最佳实践是不在类的构造函数中进行验证。 所以你的代码会有所改进(我没有运行它,并且仍有改进):

public class CD {
    String artistname = "";
    String albumname = "";
    double cdprice = 0;
    int amountinstock = 0;

    public String ValidationMessage = "";

    public CD(final String artistname, final String albumname, final double cdprice, final int amountinstock) {
        this.artistname = artistname;
        this.albumname = albumname;
        this.cdprice = cdprice;
        this.amountinstock = amountinstock;
    }

    public boolean ValidateCD()
    {
        this.ValidationMessage = "";
        if (/*insert validation condition here*/)
        {
            this.ValidationMessage = "CD IS NOT VALID BECAUSE TITLE IS WRONG";
            return false;
        }
        return true;
    }

    public static void main(final String[] arg) throws Exception {

        final CD cd1 = new CD("Muse", "The Resistance", 11.99, 20);

        final boolean isValid = cd1.ValidateCD();
        if (!isValid) {
            System.out.println(cd1.ValidationMessage);
        }

    }
}
相关问题