|
| 1 | +# @FunctionalInterface |
| 2 | + |
| 3 | +## How to throw exception in lambda |
| 4 | + |
| 5 | +Create a custom `Consumer` that throws an exception. |
| 6 | + |
| 7 | +```java |
| 8 | +import java.io.IOException; |
| 9 | +import java.nio.file.FileStore; |
| 10 | +import java.nio.file.FileSystem; |
| 11 | +import java.nio.file.FileSystems; |
| 12 | +import java.util.function.Consumer; |
| 13 | + |
| 14 | +@FunctionalInterface |
| 15 | +public interface ThrowingConsumer<T> extends Consumer<T> { |
| 16 | + |
| 17 | + @Override |
| 18 | + default void accept(final T elem) { |
| 19 | + try { |
| 20 | + acceptThrows(elem); |
| 21 | + } catch (final Exception e) { |
| 22 | + // Implement your own exception handling logic here.. |
| 23 | + // For example: |
| 24 | +// System.out.println("handling an exception..."); |
| 25 | + // Or ... |
| 26 | + throw new RuntimeException(e); |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + void acceptThrows(T elem) throws Exception; |
| 31 | + |
| 32 | +} |
| 33 | + |
| 34 | +void main(String[] args) throws IOException { |
| 35 | + |
| 36 | + FileSystem fileSystem = FileSystems.getDefault(); |
| 37 | + |
| 38 | + System.out.printf("%30s | %10s | %23s | %20s \n", "", "Type", "Total space", "Free space"); |
| 39 | + System.out.println("-------------------------------------------------" |
| 40 | + + "----------------------------------------------------------"); |
| 41 | + |
| 42 | + Iterable<FileStore> fileStores = fileSystem.getFileStores(); |
| 43 | + |
| 44 | +// for (var fileStore : fileStores) { |
| 45 | +// System.out.printf("%30s | %10s | %20s GB | %20s GB\n", fileStore, fileStore.type(), |
| 46 | +// (fileStore.getTotalSpace() / 1073741824f), |
| 47 | +// (fileStore.getUsableSpace() / 1073741824f)); |
| 48 | +// } |
| 49 | + |
| 50 | + fileStores.forEach((ThrowingConsumer<FileStore>) fileStore -> { |
| 51 | + |
| 52 | + System.out.printf("%30s | %10s | %20s GB | %20s GB\n", fileStore, fileStore.type(), |
| 53 | + (fileStore.getTotalSpace() / 1073741824f), |
| 54 | + (fileStore.getUsableSpace() / 1073741824f)); |
| 55 | + }); |
| 56 | +} |
| 57 | +``` |
0 commit comments