简体   繁体   中英

Issue creating and using my own exception class

I have a JUnit test class, which I'm new to making. 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. 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?

    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.

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 .

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 .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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