Use structured error handling to keep Java document workflows predictable. Nutrient Java SDK raises NutrientException when an SDK operation fails, so you can use standard Java exception patterns in your application.
For production systems, error handling helps you:
- Return useful feedback
- Isolate failures to individual documents
- Control fallback or retry logic
Implement error handling with the Java SDK
Nutrient Java SDK integrates with Java’s built-in exception model. Catch NutrientException to handle SDK-specific failures and keep conversion logic readable.
Prepare the project
Define a package and class:
package io.nutrient.Sample;Import SDK classes and Java NIO utilities:
import io.nutrient.sdk.Document;import io.nutrient.sdk.exceptions.NutrientException;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;
public class ErrorHandling {Validate input and catch errors
Validate the input path before processing. Then call the conversion method and catch NutrientException:
public static void main(String[] args) { String inputFile = "input.pdf"; String outputFile = "output.pdf";
// Check if input file exists before processing if (!fileExists(inputFile)) { System.err.println("Error: Input file '" + inputFile + "' not found."); System.exit(1); }
System.out.println("Opening document: " + inputFile);
try { convertDocument(inputFile, outputFile); System.out.println("Conversion completed successfully!"); System.out.println("Output file: " + outputFile); } catch (NutrientException e) { // Handle Nutrient SDK specific errors System.err.println("Nutrient SDK Error: " + e.getMessage()); System.err.println("This could be due to:"); System.err.println(" - Invalid or corrupted input file"); System.err.println(" - Unsupported file format"); System.err.println(" - License issues"); System.err.println(" - Insufficient permissions"); System.exit(1); } }Wrap SDK operations
Keep SDK calls in a dedicated method that declares throws NutrientException:
private static void convertDocument(String inputFile, String outputFile) throws NutrientException { try (Document document = Document.open(inputFile)) { System.out.println("Document opened successfully.");
System.out.println("Converting to PDF..."); document.exportAsPdf(outputFile); } }Add helper utilities
Use Java NIO to validate file existence:
private static boolean fileExists(String filePath) { Path path = Paths.get(filePath); return Files.exists(path) && Files.isRegularFile(path); }}Summary
The flow has three steps:
- Validate the input file path.
- Open and convert the document.
- Catch
NutrientExceptionand return clear error output.
Download this sample package to run the example locally.