[简单]得到Exception异常信息

         为了在发生异常时候Spring事务能回滚,在捕获异常后抛出new RuntimeException,在最终记录调用结果的方法中捕获Exception,记录下异常信息,今天发现在catch中使用e.getMessage()拿不到异常信息,如下所示:

      

       简单的写个例子,用到了反射:

      

package exception;

public class ExceptionMsgClass {
	public int methodTest(String orgIdStr) throws Exception {
		try {
			if (orgIdStr == null || Integer.parseInt(orgIdStr) < 0) {
				throw new Exception("非法参数");
			}
			int orgId = Integer.parseInt(orgIdStr);
			if (orgId < 100) {
				throw new Exception("参数数量不正确");
			}
			return orgId;
		} catch (Exception e) {
			System.out.println("准备抛出异常信息:" + e.getMessage());
			throw new RuntimeException(e.getMessage());
		}
	}

}

   调用测试:

  

package exception;

import java.lang.reflect.Method;

public class ExceptionReflectTest {
	public void reflectTest(String className,String value){
		try{
			Class c=Class.forName(className);
			Object object = c.newInstance(); 
			Method mth = object.getClass().getMethod("methodTest",String.class);
			Integer result=(Integer) mth.invoke(object, value);
			System.out.println(result);
		}catch(Exception e){
			String msg=e.getMessage();
			System.out.println("捕获异常信息:"+msg);
		}
	}
	public static void main(String[] args) {
		ExceptionReflectTest t=new ExceptionReflectTest();
		t.reflectTest("exception.ExceptionMsgClass", "13");
	}
}

 

   结果为:

  

准备抛出异常信息:参数数量不正确
捕获异常信息:null

    debug结果为:

   

      正确方法为:

     

package exception;

import java.lang.reflect.Method;

public class ExceptionReflectTest {
	public void reflectTest(String className,String value){
		try{
			Class c=Class.forName(className);
			Object object = c.newInstance(); 
			Method mth = object.getClass().getMethod("methodTest",String.class);
			Integer result=(Integer) mth.invoke(object, value);
			System.out.println(result);
		}catch(Exception e){
			String msg=e.getMessage();
			if(e.getCause() instanceof RuntimeException){
				msg=e.getCause().getMessage();
			}
			System.out.println("捕获异常信息:"+msg);
		}
	}
	public static void main(String[] args) {
		ExceptionReflectTest t=new ExceptionReflectTest();
		t.reflectTest("exception.ExceptionMsgClass", "13");
	}
}

  结果为:

  

         转载请注明原处,http://53873039oycg.iteye.com/blog/2104488 ,谢谢。

      全文完。 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值