java对异常泛型的简单实例

因为泛型具有擦除的特性,所以在现在的java中不支持try{}catch{}的catch子句中不支持对泛型的使用,为了使写的代码在异常的处理方面具有更好的泛型特性,需要在声明类的时候让泛型继承自Exception或者是Throwable,这样在对象进行实例化的时候便可以指定具体的异常类型,下面是异常泛型的小例子


/**
 * Because of erasure, the use of generics with exceptions is extremely limited.
 * A catch clause cannot catch an exception of a generic type, because the exact
 * type of the exception must be known at both compile time and run time. Also,
 * a generic class can’t directly or indirectly inherit from Throwable (this
 * further prevents you from tryi ng to define generic exceptions that can’t be
 * caught). However, type parameters may be used in the throws clause of a
 * method declaration. This allows you to write generic code that varies with
 * the type of a checked exception
 * 
 * @author Eric
 * 
 */
public class ExceptionOfGeneric {
	public static void main(String args[]) {
		ProcessRunner<String, Process1Exception> pr1 = new ProcessRunner<String, Process1Exception>();
		pr1.add(new ProcessImp1());
		try {
			System.out.println(pr1.runnAlllProcess());
		} catch (Process1Exception e) {
			e.printStackTrace();
		}
		ProcessRunner<Integer, Process2Exception> pr2 = new ProcessRunner<Integer, Process2Exception>();
		pr2.add(new ProcessImp2());
		try {
			System.out.println(pr2.runnAlllProcess());
		} catch (Process2Exception e) {
			e.printStackTrace();
		}
	}
}

interface Process<T, E extends Exception> {
	public void process(List<T> t) throws E;
}

class Process1Exception extends Exception {}

class Process2Exception extends Exception {}

class ProcessRunner<T, E extends Exception> extends ArrayList<Process<T, E>> {
	List<T> runnAlllProcess() throws E {
		List<T> results = new ArrayList<T>();
		for (Process<T, E> t : this) {
			// execute process may be throw variable type of exception
			t.process(results);
		}
		return results;
	}
}

class ProcessImp1 implements Process<String, Process1Exception> {
	
	public void process(List<String> strs) throws Process1Exception {
		strs.add("HELLO");
	}
	
}

class ProcessImp2 implements Process<Integer, Process2Exception> {
	
	public void process(List<Integer> t) throws Process2Exception {
		t.add(10);
	}
	
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值