这是原来的异常代码如何在Java中定制自定义异常?
public class NoValueForParametarException extends Exception {
private Exception nestedException;
private int errorCode;
public NoValueForParametarException(String message) {
super(message);
}
public NoValueForParametarException(Exception ex,String message) {
super(message);
this.nestedException = ex;
}
public NoValueForParametarException(String message, int errorCode) {
super(message);
this.setErrorCode(errorCode);
}
public Exception getNestedException() {
return this.nestedException;
}
public void setNestedException(Exception nestedException) {
this.nestedException = nestedException;
}
public int getErrorCode() {
return this.errorCode;
}
public void setErrorCode(int errorCode) {
this.errorCode = errorCode;
}
public String toString() {
StringBuffer errorMsg = new StringBuffer();
errorMsg.append("[" + super.getMessage() + "]:");
errorMsg.append((this.nestedException != null) ? ("\n[Nested exception]:" + this.nestedException):"");
return errorMsg.toString();
}
}
,这是新的
public class NoValueForParametarWebServiceException extends NoValueForParametarException {
public NoValueForParametarWebServiceException(String message) {
super(message);
}
public NoValueForParametarWebServiceException(Exception ex,String message) {
super(message);
this.setNestedException(ex);
}
public NoValueForParametarWebServiceException(String message, int errorCode) {
super(message);
this.setErrorCode(errorCode);
}
public String toString() {
StringBuffer errorMsg = new StringBuffer();
errorMsg.append(super.getMessage());
errorMsg.append((this.getNestedException() != null) ? ("\n[Nested exception]:" + this.getNestedException()):"");
return errorMsg.toString();
}
}
所有我需要的是改变toString()
方法的一部分,因此,而不是errorMsg.append("[" + super.getMessage() + "]:");
我有errorMsg.append(super.getMessage());
。在某个方法中,由于catch块设置为NoValueForParametarWebServiceException
未捕获原始文件,所以会抛出原始文件。我知道我可以抓到原来的,只是重新投掷新的(这也会令人满意),但我想知道是否有另一种方式。
编辑:看来我需要的是不清楚,所以要更清楚: 程序抛出NoValueForParametarException
。我想抓住它,但使用NoValueForParametarWebServiceException
(这是创建新类的唯一原因)的toString()
方法,因为我需要新版本的输出格式而不更改旧版本。
我是继承它,因为它似乎是合乎逻辑的(我需要几乎相同的行为,与一个小的toString更改)。我只是不改变原始类的原因是因为它是一个共享的类,有人可能需要这种输出格式。 – Andrija 2010-08-17 17:50:59