自定义 Exception

第一步: 定义一个Exception父类
public class BaseException extends Exception
{
    private static final long serialVersionUID = 1L;
    //异常类别  根据返回的不同数字信息得到不同的异常信息
    protected int               exceptionKey;
    //异常信息
    protected String message;

    protected Object object;   
   
    public Object getObject()
   {
       return object;
   }

   public void setObject(Object object)
   {
       this.object = object;
   }

    public String getMessage()
   {
        return message;
   }

   public void setMessage(String message)
   {
this.message = message;
   }

    public int getExceptionKey()
    {
        return this.exceptionKey;
    }

public BaseException()
    {
    }

    public BaseException(int exceptionKey)
    {
        this.exceptionKey = exceptionKey;
    }
public BaseException(String message)
    {
        this.message = message;
    }
}
第二步:然后自定义自己的异常类,继承上面的Exception父类
     public class LadingsException extends BaseException
{
static final long serialVersionUID = 1001;

final public static int UserDefined = 10000; //用户自定义错误

/**  LadingsException  */
final public static int OutQuantity = 1; //超出数量
final public static int OutWeight = 2; //超出重量
final public static int OutArea = 3; //超出面积
final public static int OutVolume = 4;//超出体积

public LadingsException(int exceptionKey)
{
super(exceptionKey);
}

public LadingsException(String message)
{
super(message);
this.exceptionKey = UserDefined;
}

public String toString()
{
return exceptionKeyToMessage();
}

public String exceptionKeyToMessage()
{
if (exceptionKey == UserDefined)
{
return message;
}
if (exceptionKey == OutQuantity)
{
return "待分配数量不足";
}

if (exceptionKey == OutArea)
{
return "待分配面积不足";
}

if (exceptionKey == OutVolume)
{
return "待分配体积不足";
}

if (exceptionKey == OutWeight)
{
return "待分配重量不足";
}

return "系统内部错误";
}

public String getMessage()
{
return exceptionKeyToMessage();
}
}
第三步使用自定义异常,在方法A通过throws LadingsException,抛到上一级中
    public  void A ()throws LadingsException{
          //调用方法B
          B();
   }
第四步在方法B中使用 throw new LadingsException(参数),抛到A中
   public  void B ()throws LadingsException{
         //判断异常是属于哪一种,然后通过LadingsException异常类的
          //构造函数,来产生异常信息
          //比如下面的就是产生  “待分配数量不足” 的异常信息
          throw new LaidngsException(LadingsException.OutQuantity);
  }
第五步从B抛到上一级A,然后在从A抛到A的上一级C中,然后在C中通过
           try{
           A();
         }catch(LaidngsException e){
              //通过e.getMessage()来获取异常信息
         }
第六步在方法C中获取到异常信息,可以通过比如Json的方式发送到前台,提示用户,该操作不能使用的原因

猜你喜欢

转载自lihongtai.iteye.com/blog/2109423