JavaCombining Exceptions in a Single Catch with Java

Combining Exceptions in a Single Catch with Java

Combining exceptions in a single catch is a handy feature developers can use when creating Java applications. In the following Java code snippet demonstrating how to catch multiple exceptions in one catch, currDir has been assigned a value that does not exist and hence will result in an exception. Enter the following code in your code editor or integrated development environment to see this in action:

Read more Java programming tutorials.

*/

import java.io.*;
import java.util.*;
import java.nio.file.*;

public class CombiningExceptions
{
	public static void main(String args[])
	{
		CombiningExceptions combiningExceptions = new CombiningExceptions();
		combiningExceptions.proceed();
	}
	
	private void proceed()
	{
		String fileTypes = "*.{java,class}";
		Path currDir = Paths.get("nonExistentFolder");
		List pathResult = new ArrayList<>();

		try (DirectoryStream directoryStream = Files.newDirectoryStream(currDir, fileTypes)) {
			for (Path filePath: directoryStream) {
				pathResult.add(filePath);
				System.out.println("Found: " + filePath);
			}
		}catch(DirectoryIteratorException | IOException exception) 
		{
			System.out.println("Exception: " + exception);
		}
	}
}

/*

You can expect the following output from running the code above:

[[email protected]]# java CombiningExceptions
Exception: java.nio.file.NoSuchFileException: nonExistentFolder

Latest Posts

Related Stories