我是Java的新手编程(实际上已经在学习),我对如何处理不同的消息有一些疑问。
我的目标是在相同的类(CustomException类)中包含这些不同的消息,以避免在每个方法上一次又一次地写入相同的字符串,从而使其他类抛出新的CustomExceptions。
直到现在我编码:
一个CustomException类,它是从Exception扩展的,具有不同的消息(示例中只有两个,但还有更多)作为字符串包括在内,当然还有构造函数:
public class CustomException class extends Exception {
private static final String MSG_ERR_NUM1 = "Error number 1";
private static final String MSG_ERR_NUM2 = "Error number 2";
public CustomException() { super(); }
public CustomException(String message) { super(message); }
public CustomException(String message, Throwable cause) { super(message, cause); }
public CustomException(Throwable cause) { super(cause); }
}
其他不同的类,上面带有某些方法的类会抛出新的CustomException:
public class Car {
public void checkWheels() throws CustomException {
if (comparison = true) {
throw new CustomException(what to call??);
}
}
}
具有main方法的类,其中执行try
和catch
:
public class Driving {
public static void main() {
try {
//doSomething
}
catch (CustomException e) {
e.printStackTrace();
}
}
}
我的问题是:
对于不同的getter方法在CustomException类上] add code从每个String中获取文本,这将是一个很好的过程吗?
public String getErrorNum1() {
return MSG_ERR_NUM1;
}
我将如何从其他类的方法中包含的方法中称这些吸气剂?
if (comparison = true) {
throw new CustomException(what here to get MSG_ERR_NUM1 or MSG_ERR_NUM2 text instead writing a String every time??);
}
感谢您的支持。
我是Java的新手编程(实际上已经在学习),我对如何处理不同的消息有一些疑问。我的目标是在同一类(CustomException类)中包括那些...
您可以将所需的字符串添加到异常的构造函数中的“消息”中,例如: