美文网首页
01. InvocationTargetException 信息

01. InvocationTargetException 信息

作者: kexue | 来源:发表于2016-06-06 18:14 被阅读96次
package com.wdxxl.InvocationTargetException;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * InvocationTargetException异常由Method.invoke(obj, args...)方法抛出。
 * 当被调用的方法的内部抛出了异常而没有被捕获时,将由此异常接收。
 */
public class InvocationTargetExceptionTest {
    public static void main(String[] args) {
        Class<?> clazz;
        try {
            clazz = Class.forName("com.wdxxl.InvocationTargetException.Reflect");
            Method method = clazz.getMethod("runInt", int.class);
            method.invoke(clazz.newInstance(), 1);
        } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | 
                 IllegalAccessException | IllegalArgumentException | InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {

            System.out.println("此处接收被调用方法内部未被捕获的异常");  
            Throwable cause = e.getCause();
            if(cause instanceof OutOfMemoryError){
                throw (OutOfMemoryError)cause;
            }if(cause instanceof Error){
                throw new Error(cause);
            }else if(cause instanceof ZeroException){
                Throwable t = e.getTargetException();
                t.printStackTrace();
            }
        }
    }
}
package com.wdxxl.InvocationTargetException;

public class Reflect {
    public void runInt(int i) throws ZeroException {
        new B().runInt(i);
    }
}

class B {
    public void runInt(int i) throws ZeroException {
        if (i == 0) { throw new OutOfMemoryError("参数不能=零"); }
        if (i == 1) { throw new Error("参数不能=1"); }
        if (i < 0) { throw new ZeroException("参数不能小于零"); }
        System.out.println("参数: " + i);
    }
}

class ZeroException extends Exception {
    private static final long serialVersionUID = 1L;
    private String message;
    public ZeroException(String message) {
        this.message = message;
    }
    public String getMessage() {
        return message;
    }
}

相关文章

网友评论

      本文标题:01. InvocationTargetException 信息

      本文链接:https://www.haomeiwen.com/subject/znfddttx.html