英文:
Error when trying to use a custom exception in a static method
问题
我有一个名为Exercise08.java的Java类。在这个类中,我创建了一个内部类HexFormatException,它继承自NumberFormatException。
public class HexFormatException extends NumberFormatException {
public HexFormatException() {
super();
}
}
我还有一个静态方法hexToDecimal(String),如果字符串不是十六进制,则应该抛出HexFormatException错误。
/**
* 将十六进制转换为十进制。
* @param hex 十六进制字符串
* @return 十六进制的十进制值
* @throws HexFormatException 如果hex不是十六进制
*/
public static int hexToDecimal(String hex) throws HexFormatException {
// 检查hex是否为十六进制,如果不是则抛出异常。
boolean patternMatch = Pattern.matches("[0-9A-F]+", hex);
if (!patternMatch)
throw new HexFormatException();
// 将hex转换为十进制
int decimalValue = 0;
for (int i = 0; i < hex.length(); i++) {
char hexChar = hex.charAt(i);
decimalValue = decimalValue * 16 + hexCharToDecimal(hexChar);
}
// 返回十进制值
return decimalValue;
}
但是,我得到了以下错误消息:
我对如何修复这个问题感到困惑。如果我抛出NumberFormatException,一切都能正常工作,但为什么对于我的自定义异常不起作用呢?
英文:
I have a java class called Exercise08.java. In this class I made the inner class HexFormatException
which extends NumberFormatException
.
public class HexFormatException extends NumberFormatException {
public HexFormatException() {
super();
}
}
I also have the static method hexToDecimal(String)
which is supposed to throw a HexFormatException
error if the String is not a hexadecimal.
/** Converts hexadecimal to decimal.
@param hex The hexadecimal
@return The decimal value of hex
@throws HexFormatException if hex is not a hexadecimal
*/
public static int hexToDecimal(String hex) throws HexFormatException {
// Check if hex is a hexadecimal. Throw Exception if not.
boolean patternMatch = Pattern.matches("[0-9A-F]+", hex);
if (!patternMatch)
throw new HexFormatException();
// Convert hex to a decimal
int decimalValue = 0;
for (int i = 0; i < hex.length(); i++) {
char hexChar = hex.charAt(i);
decimalValue = decimalValue * 16 + hexCharToDecimal(hexChar);
}
// Return the decimal
return decimalValue;
}
Instead I get this error message:
I'm really confused about how to fix this. Everything works fine if I throw a NumberFormatException
, but why doesn't it work for my custom exception?
答案1
得分: 2
在静态方法中使用内部类,该内部类也必须是静态的。 <br>
public static class HexFormatException extends NumberFormatException {
public HexFormatException() {
super();
}
}
英文:
To use inner class in static method it must be static too. <br>
public static class HexFormatException extends NumberFormatException {
public HexFormatException() {
super();
}
}
答案2
得分: 1
你已将HexFormatException定义为内部类,这意味着它属于包含它的实例。在静态方法中,没有默认的包含实例,所以会出现这个错误。
一个简单的解决方法是使用static
关键字声明该类:
public static class HexFormatException ...
英文:
You've made HexFormatException an inner class which means it belongs to an enclosing instance. In at static method there is no default enclosing instance so you get this error.
A simple fix is to declare the class with static
:
public static class HexFormatException ...
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论