目录
1,问题场景:
我们通常在java开发中采用自定义异常,在业务中遇到非系统错误时抛出自定义异常,并在上层进行捕获,就能知道业务的具体出错信息。这种方法很常用,但是如果采用反射去自动调用某个方法时,却不能捕获到用户自定义的异常。
1.1代码演示如下:
其中BusinessException是自定义异常
定义Man对象,里面的setWork方法抛出自定义BusinessException异常
package com.cc.utils;
import com.cc.tools.exception.BusinessException;
/**
* @author 作者 Your-Name:Pxy
* @version 创建时间:2020年11月26日 下午6:27:00
* 类说明
*/
public class Man {
private String work;
public String getWork() {
return work;
}
public void setWork(String work) {
this.work = work;
System.out.println(work);
throw new BusinessException("man is died", true);
}
}
main方法利用反射调用Man中的setWork方法,捕获异常
package com.cc.utils;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import com.cc.tools.exception.BusinessException;
/**
*
* @author 作者 Your-Name:Pxy
*
* @version 创建时间:2020年11月26日 下午6:26:19
*
* 类说明
*
*/
public class TestDemo {
public static void main(String[] args) {
Method method = null;
try {
method = Man.class.getMethod("setWork", String.class);
} catch (NoSuchMethodException | SecurityException e) {
e.printStackTrace();
}
Man man = new Man();
try {
method.invoke(man, "man is hard working");
} catch (Exception e) {
System.out.println("ok,we catch SimpleException:"+e);
}
}
}
打印结果
man is hard working
ok,we catch SimpleException:java.lang.reflect.InvocationTargetException
2,问题解决:
这里我们看到异常被捕捉到了,但是打印的异常不是 BusinessException异常,而是反射异常。这是为什么呢?其实java认为用反射来调用方法时,jvm不能在编译期间确定方法的throws 类型,所以方法可能抛出的异常jvm也不能动态确定其类型,而统一抛出InvocationTargetException。那么我们怎么修改以上代码能正确地获取到业务抛出的异常信息呢?这里我们给出一个重要的方法,getCause()方法。getCause()返回此异常的原因(尝试加载类时发生错误引发的异常;否则返回 null)
2.1代码演示
那么,我们修改main方法如下
package com.sgcc.utils; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import com.sgcc.tools.exception.BusinessException; /** * * @author 作者 Your-Name:Pxy * * @version 创建时间:2020年11月26日 下午6:26:19 * * 类说明 * */ public class TestDemo { public static void main(String[] args) { Method method = null; try { method = Man.class.getMethod("setWork", String.class); } catch (NoSuchMethodException | SecurityException e) { e.printStackTrace(); } Man man = new Man(); try { method.invoke(man, "man is hard working"); } catch (Exception e) { Throwable cause = e.getCause(); System.out.println("ok,we catch SimpleException:"+cause); } } }
执行结果如下:
man is hard working
ok,we catch SimpleException:com.sgcc.tools.exception.BusinessException: man is died捕捉到原方法中的 BusinessException异常