java 自定义异常

1. 系统中一定要有自定义异常

 

2. 通过自定义异常将系统中发生的异常信息转换为自己的异常信息

 

3. 自定义异常继承于Exception。说明自定义异常是checked exception

 

4. 自定义异常信息来自于哪里?


5. 对于一个完整的系统来说,通常都有一个异常信息属性文件用于存放系统当中的异常信息。

 

6. 需要一种机制从属性文件当中读取异常信息

 

7. 对于系统来说,完整的异常处理机制需要如下文件


   a) 异常信息属性文件(key = value)
   b) 读取异常信息的类
   c) 可以将key定义在一个类中,比如完全用数字标识的成员变量

   例如
       public class ErrorCode {
            public int DELETE_ERROR = 10001;
       }


8. 通用模式:读取资源文件用 resourcebundle

   

----------------------------------------------------------------------------

   1). 自定义异常测试类 TestException

 

public class TestException {

	public static final int DELE = 10001;

	private static void testMathException() throws EngineException {
		try {
			int a = 0;
			int b = 2;

			System.out.println(b / a);

		} catch (Exception e) {
			e.printStackTrace();
			throw new EngineException("除数不能为0!");
		}
	}
	
	@SuppressWarnings("unused")
	private static void testMyException() throws EngineException {
		
		int[] arr = null;
		
		if ( arr == null || arr.length == 0) {
			throw new EngineException(DELE);
		}
	}
	
	public static void main(String[] args) throws Exception {

		testMathException();
		
		testMyException();
	}
}

 

  

   2). 自定义异常类 EngineException

   

public class EngineException extends Exception {
	
	/**
	 * serialVersionUID用来作为Java对象序列化中的版本标示之用; 
	 * 如果一个序列化类没有声明这样一个static final的产量,JVM会根据各种参数为这个类计算一个; 
	 * 对于同样一个类,不同版本的JDK可能会得出不同的serivalVersionUID
	 */
	private static final long serialVersionUID = 1L;
	
	private int errorCode;

	public int getErrorCode() {
		return errorCode;
	}

	public void setErrorCode(int errorCode) {
		this.errorCode = errorCode;
	}
	
	public EngineException(int errorCode) {
		super(MessageHelper.getExceptionByErrorCode(errorCode));
		this.errorCode = errorCode;
	}
	
	public EngineException(int errorCode, Throwable throwable) {
		super(MessageHelper.getExceptionByErrorCode(errorCode), throwable);
		this.errorCode = errorCode;
	}
	
	public EngineException(String message, Throwable throwable) {
		super(message, throwable);
	}
	
	public EngineException(String message) {
		super(message);
	}
	
	public String getErrorMessage(int errorCode) {
		return MessageHelper.getExceptionByErrorCode(errorCode);
	}
	
}

 

   3). 自定义异常获取本地资源类 MessageHelper

  

public class MessageHelper {
	
	public static String getExceptionByErrorCode(int errorCode) {
		
		ResourceBundle rb = ResourceBundle.getBundle("message_zh_CN", Locale.getDefault());
		
		String message = rb.getString(String.valueOf(errorCode));
		
		return message;
	}
	
}

   4). 资源文件 message_zh_CN.properties

10001=My Exception

 

   

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值