Java 自定义错误类示例代码

在程序中,需要抛出异常,然后在用户界面进行错误信息输出

一种情况是在程序中最后UI显示的时候一个一个异常捕获,然后 显示对应的ErrorMessage,有时候,程序因为业务逻辑的原因需要抛出异常,就需要自定义异常。

如何将异常消息集中处理,以对应多语言话的要求 ,这些错误消息就需要集中处理了。

自定义错误消息。


public class MyException extends Exception
{
    private static final long serialVersionUID = 1L;
    private Type type;

    public MyException( Type type )
    {
        super();
        this.type = type;
    }
    public MyException( Throwable t,Type type )
    {
        super( t );
        this.type = type;
    }
    public String toString() {
        return super.toString() + "<" + getErrorType().getErrorCode() + ">";
    }

    public Type getErrorType()
    {
        return type;
    }

    public enum Type
    {
        // 系统错误
        SYstem_ERROR( "99999" ),

        // 用户认证错误
        USER_AUTH( "03003" );

        private String errorCode;
        Type( String errorCode )
        {
            this.errorCode = errorCode;
        }
        public String getErrorCode()
        {
            return this.errorCode;
        }
    }
}

在这里抛出错误代码,然后可以根据这个错误代码取得资源文件错误消息。

相关文章

HashMap是Java中最常用的集合类框架,也是Java语言中非常典型...
在EffectiveJava中的第 36条中建议 用 EnumSet 替代位字段,...
介绍 注解是JDK1.5版本开始引入的一个特性,用于对代码进行说...
介绍 LinkedList同时实现了List接口和Deque接口,也就是说它...
介绍 TreeSet和TreeMap在Java里有着相同的实现,前者仅仅是对...
HashMap为什么线程不安全 put的不安全 由于多线程对HashMap进...