2015-05-11 24 views
7

Aşağıdaki kodum var.Özel kontrol edilen istisna java8 lambda ifadesiyle nasıl atılır?

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 
} 

İşte benim process(String line) yöntem kontrol istisna atar ve lambda içinden bu yöntemi çağırıyorum. Bu noktada, RuntimeException atmadan MyExceptionreadStreamWithjava8() yönteminden atmanız gerekir.

Bunu java8 ile nasıl yapabilirim?

+3

Not: "Files.lines()" – assylias

+0

@assylias ile kaynakları kullanmayı deneyin. Bazı örnek kodları paylaşabilir misiniz? – user3496599

+1

'(Stream lines = Files.lines (Paths.get (...))) {...}} ve sonuncu bloğu kaldırın. – assylias

cevap

5

Kısa cevap yapamayacağınızdır. Bunun nedeni, forEachOrdered'un Consumer alması ve Consumer.accept'un herhangi bir özel durum atmak için bildirilmemesidir.

geçici çözüm Genellikle process yönteminin içine özel durum işlemek veya for-döngüler ile o eski okul yolu yapmak bu gibi durumlarda,

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); 
} 
Ancak

gibi bir şey yapmaktır.

İlgili konular