简体   繁体   English

创建和使用我自己的异常类时出现问题

[英]Issue creating and using my own exception class

I have a JUnit test class, which I'm new to making. 我有一个JUnit测试类,这是我的新手。 I also trying to learn how to make my own exception classes. 我还尝试学习如何制作自己的异常类。 I have been creating a BigInt class, and one of the constructors takes in Strings. 我一直在创建BigInt类,其中一个构造函数采用Strings。 This bit of code is looping through an array, and its supposed to be checking if the character at each position is an integer. 这一段代码在一个数组中循环,它应该检查每个位置的字符是否为整数。 Right now there is an error that says "Unreachable catch block for BigIntFormatException. This exception is never thrown from the try statement body" Any ideas for why? 现在有一个错误,指出“ BigIntFormatException的Unreachable catch块。永远不会从try语句主体中引发此异常”。为什么会有任何想法?

    String[] s = { " - - 1424", "+ + 14324", "a142432", "1432 3413",
            "+242134.32421", "", "    \n", "\t ++" };
    for (int i = 0; i < s.length; i++) {
        try {
            BigInt b = new BigInt(s[i]);
            assertFalse(true);
        } catch (BigIntFormatException e) {
            assertTrue(true);
        }
    }

So far this is what my BigIntFormatException class just looks like, so any help with this part would be appreciated too. 到目前为止,这就是我的BigIntFormatException类的样子,因此对此部分的任何帮助也将不胜感激。

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

Simply put, this compilation failure is quite clear: neither the constructor to BigInt nor the assertion declare that they are going to throw BigIntFormatException . 简而言之,这种编译失败非常明显: BigInt的构造函数和断言均未声明将要抛出BigIntFormatException

Since Exception is the class of checked exceptions (meaning that you do have to wrap them in a try-catch block), you must declare them to be thrown in your constructor of BigInt . 由于Exception是已检查异常的类(意味着您必须将它们包装在try-catch块中),因此必须声明将它们抛出到BigInt的构造函数中。

Here's the way you would do that. 这就是您要执行的操作。

public BigInt(String str) throws BigIntFormatException {
    // logic
}

You need to throw the exception in your BigInt class 您需要在BigInt类中引发异常

    if(/*error condition*/) {
        throw new BigIntFormatException("your message");
    }

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

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