java 自定义异常,以及捕获异常

在编写内容之前,先简单介绍一下java的异常,

异常分为两大类,运行时异常(RuntimeException)和除了运行时异常之外的其他异常(编译时异常)。

好多程序猿在异常的处理上都是比较模糊或者笼统的,有的是在catch代码块里面直接e.printStackTrace()就不管了,其实这种操作为程序哪一个环节出错很不容易排查。好了不多废话了,来点干活。

自定义异常类:BaseException:

public class BaseException extends Exception {
	private static String errorMessage;
	private static String errorCode;

	public BaseException(String errorCode,String errorMessage){
		super(errorMessage);
		this.errorCode = errorCode;
		this.errorMessage = errorMessage;
	}
	
	public static String getErrorMessage() {
		return errorMessage;
	}

	public static String getErrorCode() {
		return errorCode;
	}

	public static void setErrorCode(String errorCode) {
		BaseException.errorCode = errorCode;
	}

	public static void setErrorMessage(String errorMessage) {
		BaseException.errorMessage = errorMessage;
	}

}

有了自定义异常类,怎么用:

public class ExceptionDemo {
	public static void main(String[] args){	
		try {
			setName();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			//判断异常是否是自己抛出的异常
			if(e instanceof BaseException){
				System.out.println("自己抛出的异常,"+e.getMessage());
			}else{
				System.out.println("不是自己抛出的异常");
			}
		}
		
	}
	
	public static  void setName() throws Exception{
		try {
			int[] a = {};
			System.out.println(a[1]);
		} catch (ArrayIndexOutOfBoundsException e) {
			// TODO: handle exception
			//抛出异常,不属于自定义异常
			throw e;
		}
		//抛出自定义异常,方便排查问题
		throw new BaseException("100", "哈哈哈");
	}
}

从上面的代码块来看,捕获异常通过  e instanceof BaseException 来判断是否自定义异常

if(e instanceof BaseException){
				System.out.println("自己抛出的异常,"+e.getMessage());
			}else{
				System.out.println("不是自己抛出的异常");
			}

通过这种处理,在项目开发过程中,很容易取处理系统内部的业务错误异常信息。

转载于:https://my.oschina.net/u/3884046/blog/1921548

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值