为了在发生异常时候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 ,谢谢。
全文完。