编写自定义异常的最佳方法

时间:2014-09-03 12:42:58

标签: java exception-handling

我正在尝试使用3个构造函数编写自定义异常。我可以在3个不同的构造函数中初始化最终变量吗?我收到编译错误。如何使这个错误免费?

    public class CrifServiceFaultException extends RuntimeException {

        /**
         * 
         */
        private static final long serialVersionUID = 1L;

        public CrifServiceFaultException(String message) {  
// // - The blank final field errorDescription may not have been 
            super(message);
        }

        public CrifServiceFaultException(String processCode,
                String processDescription, String transformCode,
                String transformDescription) {  
// - The blank final field errorDescription may not have been 
     initialized
            super(processDescription + " " + transformDescription);
            this.processCode = processCode;
            this.processDescription = processDescription;
            this.transformCode = transformCode;
            this.transformDescription = transformDescription;
        }

        public CrifServiceFaultException(String errorCode, String errorDescription) {            // The blank final field transformDescription may not have been initialized

            super(errorDescription);
            setErrorCode(errorCode);
            setErrorDescription(errorDescription);
        }

        final private String processCode;
        final private String processDescription;
        final private String transformCode;
        final private String transformDescription;
        final private String errorCode;
        final private String errorDescription;
    // getters are here

    }

1 个答案:

答案 0 :(得分:2)

因为,根据Java specifications每个最终变量必须在构造函数结束之前初始化。

在每个构造函数的情况下,您将其中一些保留为未初始化(正式地,它们空白)。简而言之,您必须为它们设置一个值(即使在特定构造函数中未使用):

public CrifServiceFaultException(String message)
{
    super(message);

    processCode = "";
    processDescription = "";
    transformCode= "";
    transformDescription= "";
    errorCode= "";
    errorDescription= "";
}

public CrifServiceFaultException(String processCode,
        String processDescription, String transformCode,
        String transformDescription)
{

    super(processDescription + " " + transformDescription);
    this.processCode = processCode;
    this.processDescription = processDescription;
    this.transformCode = transformCode;
    this.transformDescription = transformDescription;

    errorCode= "";
    errorDescription= "";
}

public CrifServiceFaultException(String errorCode, String errorDescription)
{
    super(errorDescription);
    setErrorCode(errorCode);
    setErrorDescription(errorDescription);

    processCode = "";
    processDescription = "";
    transformCode= "";
    transformDescription= "";
}

请注意,即使文档说明:

  

...声明变量final可以作为有用的文档......

从这句话我们可以猜到final只是一个装饰对于避免编译时的琐碎错误很有用(实际上与C {+ {}}非常相似)。无论如何IMO我们不应该假设const变量是可变的(即使是通过JNI),因为他们可以在运行时启用强大的优化(我特意想到HotSpot) ):考虑并发访问和缓存一致性(特别是对于原始类型)。