若要在异常中添加附加信息,则可以为类添加一些变量和方法。本例演示的自定义异常没有按照业务类型来命名,而是创建一个通用异常类,以retCd来区别发生异常的业务类型与发生位置,当然对于具体的retCd值,事先必须有具体的规定或说明。
/**
* 多数情况下,创建自定义异常需要继承Exception,本例继承Exception的子类RuntimeException
* @author Mahc
*
*/
public class CustomerException extends RuntimeException {
private String retCd ; //异常对应的返回码
private String msgDes; //异常对应的描述信息
public CustomerException() {
super();
}
public CustomerException(String message) {
super(message);
msgDes = message;
}
public CustomerException(String retCd, String msgDes) {
super();
this.retCd = retCd;
this.msgDes = msgDes;
}
public String getRetCd() {
return retCd;
}
public String getMsgDes() {
return msgDes;
}
}public class TestClass {
public void testException() throws CustomerException {
try {
<p> //..some code that throws <span style="font-family:SimSun;">CustomerException</span></p> } catch (Exception e) {
throw new CustomerException("14000001", "String[] strs's length < 4");
}
}
}public class TestCustomerException {
public static void main(String[] args) {
try {
TestClass testClass = new TestClass();
testClass.testException();
} catch (CustomerException e) {
e.printStackTrace();
System.out.println("MsgDes\t"+e.getMsgDes());
System.out.println("RetCd\t"+e.getRetCd());
}
}
}以下的自定义异常的最佳实践,摘自网络,经过参考扩展使用。public void dataAccessCode (){
Connection conn = null;
try{
conn = getConnection ();
..some code that throws SQLException
}catch(SQLException ex){
ex.printStacktrace ();
} finally{
DBUtil.closeConnection (conn);
}
}
class DBUtil{
public static void closeConnection
(Connection conn){
try{
conn.close ();
} catch(SQLException ex){
logger.error ("Cannot close connection");
throw new RuntimeException (ex);
}
}
}public void useExceptionsForFlowControl () {
try {
while (true) {
increaseCount ();
}
} catch (MaximumCountReachedException ex) {
}
//Continue execution }
public void increaseCount ()
throws MaximumCountReachedException {
if (count >= 5000)
throw new MaximumCountReachedException ();
}try{
..
}catch(Exception ex){
}
【转载使用,请注明出处:http://blog.csdn.net/mahoking】
【转载使用,请注明出处:http://blog.csdn.net/mahoking】
原文:http://blog.csdn.net/mahoking/article/details/45064259