捕获java反射执行方法抛出的异常

来源:互联网 发布:聚划算 淘宝 编辑:程序博客网 时间:2024/06/05 04:38

一般在业务开发时需要向上层抛异常写法如下:

public void A() throws Exception{  throw new Exception();}public void B(){  try{    A();  }catch(Exception e){    //具体处理异常  }}

但是如果是通过反射调用的A方法那么如果直接catch异常类Exception
会返回null,所以应该用如下方法捕获:

public String handleException() {        String msg = null;        try {            Object o = Class.forName("xxx.xxx").newInstance();            o.getClass().getMethod("").invoke(o);        } catch (Exception e) {            if (e instanceof InvocationTargetException) {                Throwable targetEx =((InvocationTargetException)e).getTargetException();                if (targetEx != null) {                    msg = targetEx.getMessage();                }            } else {                msg = e.getMessage();            }        }        return msg;    }
原创粉丝点击