自定义 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的方式发送到前台,提示用户,该操作不能使用的原因

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值