Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用java8 lambda表达式引发自定义检查异常?_Java_Java 8 - Fatal编程技术网

如何使用java8 lambda表达式引发自定义检查异常?

如何使用java8 lambda表达式引发自定义检查异常?,java,java-8,Java,Java 8,我有下面的代码 private static void readStreamWithjava8() { Stream<String> lines = null; try { lines = Files.lines(Paths.get("b.txt"), StandardCharsets.UTF_8); lines.forEachOrdered(line -> process(line)); } catch (IOExc

我有下面的代码

private static void readStreamWithjava8() {

    Stream<String> lines = null;

    try {
        lines = Files.lines(Paths.get("b.txt"), StandardCharsets.UTF_8);
        lines.forEachOrdered(line -> process(line));
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (lines != null) {
            lines.close();
        }
    }
}

private static void process(String line) throws MyException {
    // Some process here throws the MyException
}
private static void readStreamWithjava8(){
流线=空;
试一试{
lines=Files.lines(path.get(“b.txt”)、StandardCharsets.UTF_8);
行。按顺序(行->流程(行));
}捕获(IOE异常){
e、 printStackTrace();
}最后{
如果(行!=null){
行。关闭();
}
}
}
私有静态无效进程(字符串行)抛出MyException{
//这里的某个进程抛出MyException
}
这里,我的
进程(字符串行)
方法抛出选中的异常,我从lambda中调用该方法。此时需要从
readStreamWithjava8()
方法中抛出
MyException
,而不抛出
RuntimeException


如何使用java8实现这一点

简而言之,你不能。这是因为
forEachOrdered
接受
使用者
,并且
使用者.accept
未声明引发任何异常

解决方法是执行以下操作

List<MyException> caughtExceptions = new ArrayList<>();

lines.forEachOrdered(line -> {
    try {
        process(line);
    } catch (MyException e) {
        caughtExceptions.add(e);
    }
});

if (caughtExceptions.size() > 0) {
    throw caughtExceptions.get(0);
}
List-caughtExceptions=new-ArrayList();
行。forEachOrdered(行->{
试一试{
工艺(生产线);
}捕获(MyException e){
添加(e)项;
}
});
如果(caughtExceptions.size()>0){
抛出caughtExceptions.get(0);
}


但是,在这些情况下,我通常会在
进程
方法中处理异常,或者用for循环的老方法来处理异常。

注意:您可以使用
文件.lines()的资源来尝试(Stream lines=Files.lines(path.get(…){…}
并删除finally块。@assylas问题是我的进程()方法抛出选中的异常,我如何才能从readStreamWithjava8()方法中抛出它。@user3496599,try with resources不是为了解决您的问题。这是关于编写更短的代码。另请参见和