java8 Lambda 异常处理

异常接口

public  class Try {
	public static <T> Consumer<? super T> of(UncheckedConsumer<T> action) {
		Objects.requireNonNull(action);
		return t -> {
			try {
				action.accept(t);
			} catch (Exception e) {
				throw new RuntimeException("Error: " + e.getMessage());
			}
		};
	}

	@FunctionalInterface
	public interface UncheckedConsumer<T> {
		void accept(T t) throws Exception;
	}
}

演示 by zero

List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5, 6, 0);
integers.forEach( Try.of(i -> System.out.println(50 / i)));
posted @ 2024-04-08 10:57  vx_guanchaoguo0  阅读(19)  评论(0编辑  收藏  举报