一般在业务开发时需要向上层抛异常写法如下:
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;
}