예외가 발생해도 계속 진행하고, 마지막에 예외 발생하기

2024. 11. 6. 23:33Java

public class FileUtils {
	public static List<Path> getFiles(String directory) {
		try(Stream<Path> filePaths = Files.walk(Paths.get(directory))) {
			return filePaths
					.filter(Files::isRegularFile)
					.collect(Collectors.toList());
		} catch(IOException e) {
			e.printStackTrace();
			return List.of();
		}
	}
}

public class Main {
    public static void main(String[] args) {
        List<Path> files = FileUtils.getFiles("/attach/abc");

		List<Exception> exList = new ArrayList<>();
		List<String> messageList = new ArrayList<>();
		for(Path path : files) {
			try {
				path.toFile().delete();	
			} catch(Exception e) {
				e.printStackTrace();
				exList.add(e);
				messageList.add(e.getMessage());
			}
		}
		
		if(exList.size() > 0) {
			ExecutionException combinedException = new ExecutionException(messageList.toString(), null);
			for(Exception e : exList) {
				combinedException.addSuppressed(e);
			}
			
			throw combinedException;
		}
    }
}