How to Handle Errors and Debug Barcode Operations in C#

Barcode processing pipelines fail silently more often than they fail loudly. A read operation returns zero results and the caller treats it as "no barcode present" — but the real cause is a corrupted file, a password-protected PDF, or a format mismatch that a log entry would have surfaced immediately. Structured error handling turns these invisible failures into actionable diagnostics.

IronBarcode provides a typed exception hierarchy under the IronBarCode.Exceptions namespace, a built-in logging API through IronSoftware.Logger, and rich BarcodeResult properties that expose confidence scores, detected format, and coordinates for every successful decode. We walk through exception handling, diagnostic extraction, logging configuration, and batch error isolation below.

Quickstart: Handle Barcode Errors and Enable Diagnostics

Wrap read/write calls in try-catch blocks targeting IronBarcode's typed exceptions to surface actionable error messages instead of silent failures.

  1. Install IronBarcode with NuGet Package Manager

    PM > Install-Package BarCode
  2. Copy and run this code snippet.

    using IronBarCode;
    using IronBarCode.Exceptions;
    
    try
    {
        BarcodeResults results = BarcodeReader.Read("label.pdf");
        Console.WriteLine($"Found {results.Count} barcode(s)");
    }
    catch (IronBarCodeFileException ex)
    {
        Console.Error.WriteLine($"File error: {ex.Message}");
    }
  3. Deploy to test on your live environment

    Start using IronBarcode in your project today with a free trial

    arrow pointer

How to Catch and Interpret IronBarcode Exceptions?

We handle IronBarcode exceptions by catching them from most specific to most general. The IronBarCode.Exceptions namespace defines 11 exception types, each mapping to a distinct failure mode. Ordering catch blocks from narrowest to widest type gives us precise control over recovery logic.

IronBarcode Exception Types — Causes and Recommended Fixes
Exception TypeTriggerRecommended Fix
IronBarCodeFileExceptionFile path invalid, file locked, or unsupported image formatValidate file exists and is accessible before calling Read()
IronBarCodePdfPasswordExceptionPDF is password-protected or encryptedSupply password via PdfBarcodeReaderOptions, or skip file and log
IronBarCodeEncodingExceptionGeneric encoding failure during barcode generationVerify input data matches the target BarcodeWriterEncoding constraints
IronBarCodeContentTooLongEncodingExceptionValue exceeds the character limit for the selected symbologyTruncate data or switch to a higher-capacity format (QR, DataMatrix)
IronBarCodeFormatOnlyAcceptsNumericValuesEncodingExceptionNon-numeric characters passed to a numeric-only format (EAN, UPC)Sanitize input or switch to an alphanumeric format (Code128, Code39)
IronBarCodeUnsupportedRendererEncodingExceptionSelected BarcodeEncoding is not writable by IronBarcodeUse BarcodeWriterEncoding enum instead of BarcodeEncoding
IronBarCodeParsingExceptionStructured data (GS1-128) fails validation during parsingValidate GS1 structure with Code128GS1Parser.IsValid() before parsing
IronBarCodeNativeExceptionError in native interop layer (missing DLLs, platform incompatibility)Verify platform-specific NuGet packages are installed (BarCode.Linux, BarCode.macOS)
IronBarCodeConfidenceThresholdExceptionInvalid confidence threshold argument passed to reader optionsEnsure ConfidenceThreshold is between 0.0 and 1.0
IronBarCodeUnsupportedExceptionOperation not supported in the current contextCheck the changelog for feature availability in your version
IronBarCodeExceptionBase type — catches any IronBarcode-specific error not matched aboveLog full exception details and escalate for investigation

We order catch blocks from the most actionable exceptions (file, PDF password, encoding) to the base type. Exception filters with when clauses let us route overlapping types without deep nesting:

//:path=/static-assets/barcode/content-code-examples/how-to/detailed-error-messages/exception-hierarchy.cs
using IronBarCode;
using IronBarCode.Exceptions;

string filePath = "warehouse-labels.pdf";

try
{
    BarcodeResults results = BarcodeReader.Read(filePath);
    foreach (BarcodeResult result in results)
    {
        Console.WriteLine($"[{result.BarcodeType}] {result.Value} (Confidence: {result.Confidence})");
    }
}
catch (IronBarCodePdfPasswordException ex)
{
    Console.Error.WriteLine($"PDF requires password: {filePath} — {ex.Message}");
}
catch (IronBarCodeFileException ex)
{
    Console.Error.WriteLine($"Cannot read file: {filePath} — {ex.Message}");
}
catch (IronBarCodeNativeException ex) when (ex.Message.Contains("DLL"))
{
    Console.Error.WriteLine($"Missing native dependency: {ex.Message}");
}
catch (IronBarCodeException ex)
{
    Console.Error.WriteLine($"IronBarcode error: {ex.GetType().Name} — {ex.Message}");
}
//:path=/static-assets/barcode/content-code-examples/how-to/detailed-error-messages/exception-hierarchy.cs
using IronBarCode;
using IronBarCode.Exceptions;

string filePath = "warehouse-labels.pdf";

try
{
    BarcodeResults results = BarcodeReader.Read(filePath);
    foreach (BarcodeResult result in results)
    {
        Console.WriteLine($"[{result.BarcodeType}] {result.Value} (Confidence: {result.Confidence})");
    }
}
catch (IronBarCodePdfPasswordException ex)
{
    Console.Error.WriteLine($"PDF requires password: {filePath} — {ex.Message}");
}
catch (IronBarCodeFileException ex)
{
    Console.Error.WriteLine($"Cannot read file: {filePath} — {ex.Message}");
}
catch (IronBarCodeNativeException ex) when (ex.Message.Contains("DLL"))
{
    Console.Error.WriteLine($"Missing native dependency: {ex.Message}");
}
catch (IronBarCodeException ex)
{
    Console.Error.WriteLine($"IronBarcode error: {ex.GetType().Name} — {ex.Message}");
}
Imports IronBarCode
Imports IronBarCode.Exceptions

Dim filePath As String = "warehouse-labels.pdf"

Try
    Dim results As BarcodeResults = BarcodeReader.Read(filePath)
    For Each result As BarcodeResult In results
        Console.WriteLine($"[{result.BarcodeType}] {result.Value} (Confidence: {result.Confidence})")
    Next
Catch ex As IronBarCodePdfPasswordException
    Console.Error.WriteLine($"PDF requires password: {filePath} — {ex.Message}")
Catch ex As IronBarCodeFileException
    Console.Error.WriteLine($"Cannot read file: {filePath} — {ex.Message}")
Catch ex As IronBarCodeNativeException When ex.Message.Contains("DLL")
    Console.Error.WriteLine($"Missing native dependency: {ex.Message}")
Catch ex As IronBarCodeException
    Console.Error.WriteLine($"IronBarcode error: {ex.GetType().Name} — {ex.Message}")
End Try
$vbLabelText   $csharpLabel

The when (ex.Message.Contains("DLL")) filter on IronBarCodeNativeException routes missing-dependency errors to a specific handler without consuming other native exceptions. This pattern is particularly useful in Docker deployments where platform-specific packages may be missing.

Note that IronSoftware.Exceptions.LicensingException is thrown separately when the license key is invalid or absent. We recommend catching it at application startup rather than around individual read/write calls.


How to Extract Diagnostic Details from Failed Reads?

A read operation that returns zero results is not an exception — it is an empty BarcodeResults collection. We extract diagnostic context by inspecting the input parameters, the options we configured, and any partial results that did come back.

The BarcodeResult object exposes several properties useful for post-mortem analysis: BarcodeType, Value, Confidence, X/Y coordinates, PageNumber, BarcodeImage, and BinaryValue. When results are present but unexpected, the Confidence property is the first value to inspect.

//:path=/static-assets/barcode/content-code-examples/how-to/detailed-error-messages/diagnostic-logging.cs
using IronBarCode;

string filePath = "scanned-invoice.png";

var options = new BarcodeReaderOptions
{
    ExpectBarcodeTypes = BarcodeEncoding.Code128 | BarcodeEncoding.QRCode,
    Speed = ReadingSpeed.Detailed,
    ExpectMultipleBarcodes = true
};

BarcodeResults results = BarcodeReader.Read(filePath, options);

if (results == null || results.Count == 0)
{
    // No barcodes detected — log the full diagnostic context
    Console.Error.WriteLine($"[WARN] No barcodes found in: {filePath}");
    Console.Error.WriteLine($"  ExpectedTypes: {options.ExpectBarcodeTypes}");
    Console.Error.WriteLine($"  Speed: {options.Speed}");
    Console.Error.WriteLine($"  Action: Retry with ReadingSpeed.ExtremeDetail or broaden ExpectBarcodeTypes");
}
else
{
    foreach (BarcodeResult result in results)
    {
        // Flag low-confidence reads for manual review
        string flag = result.Confidence < 80 ? " ⚠ LOW_CONFIDENCE" : "";
        Console.WriteLine($"[{result.BarcodeType}] {result.Value} "
            + $"(Confidence: {result.Confidence}%, Page: {result.PageNumber}, "
            + $"Position: {result.X},{result.Y}){flag}");
    }
}
//:path=/static-assets/barcode/content-code-examples/how-to/detailed-error-messages/diagnostic-logging.cs
using IronBarCode;

string filePath = "scanned-invoice.png";

var options = new BarcodeReaderOptions
{
    ExpectBarcodeTypes = BarcodeEncoding.Code128 | BarcodeEncoding.QRCode,
    Speed = ReadingSpeed.Detailed,
    ExpectMultipleBarcodes = true
};

BarcodeResults results = BarcodeReader.Read(filePath, options);

if (results == null || results.Count == 0)
{
    // No barcodes detected — log the full diagnostic context
    Console.Error.WriteLine($"[WARN] No barcodes found in: {filePath}");
    Console.Error.WriteLine($"  ExpectedTypes: {options.ExpectBarcodeTypes}");
    Console.Error.WriteLine($"  Speed: {options.Speed}");
    Console.Error.WriteLine($"  Action: Retry with ReadingSpeed.ExtremeDetail or broaden ExpectBarcodeTypes");
}
else
{
    foreach (BarcodeResult result in results)
    {
        // Flag low-confidence reads for manual review
        string flag = result.Confidence < 80 ? " ⚠ LOW_CONFIDENCE" : "";
        Console.WriteLine($"[{result.BarcodeType}] {result.Value} "
            + $"(Confidence: {result.Confidence}%, Page: {result.PageNumber}, "
            + $"Position: {result.X},{result.Y}){flag}");
    }
}
Imports IronBarCode

Dim filePath As String = "scanned-invoice.png"

Dim options As New BarcodeReaderOptions With {
    .ExpectBarcodeTypes = BarcodeEncoding.Code128 Or BarcodeEncoding.QRCode,
    .Speed = ReadingSpeed.Detailed,
    .ExpectMultipleBarcodes = True
}

Dim results As BarcodeResults = BarcodeReader.Read(filePath, options)

If results Is Nothing OrElse results.Count = 0 Then
    ' No barcodes detected — log the full diagnostic context
    Console.Error.WriteLine($"[WARN] No barcodes found in: {filePath}")
    Console.Error.WriteLine($"  ExpectedTypes: {options.ExpectBarcodeTypes}")
    Console.Error.WriteLine($"  Speed: {options.Speed}")
    Console.Error.WriteLine("  Action: Retry with ReadingSpeed.ExtremeDetail or broaden ExpectBarcodeTypes")
Else
    For Each result As BarcodeResult In results
        ' Flag low-confidence reads for manual review
        Dim flag As String = If(result.Confidence < 80, " ⚠ LOW_CONFIDENCE", "")
        Console.WriteLine($"[{result.BarcodeType}] {result.Value} " &
                          $"(Confidence: {result.Confidence}%, Page: {result.PageNumber}, " &
                          $"Position: {result.X},{result.Y}){flag}")
    Next
End If
$vbLabelText   $csharpLabel

Three patterns commonly surface during diagnostics. First, empty results with a narrow ExpectBarcodeTypes setting usually means the actual barcode is a different symbology — broadening to BarcodeEncoding.All confirms this. Second, low-confidence reads below 70% often indicate poor image quality, and applying image filters (contrast, sharpening, adaptive threshold) before retrying typically resolves the issue. Third, the RemoveFalsePositive option in BarcodeReaderOptions can be toggled to eliminate phantom reads from noisy backgrounds.


How to Enable Verbose Logging for Barcode Operations?

IronBarcode exposes a built-in logging API through the shared IronSoftware.Logger class. We set the logging mode and file path before any barcode operations to capture internal diagnostic output from the library's read and write pipelines.

//:path=/static-assets/barcode/content-code-examples/how-to/detailed-error-messages/enable-logging.cs
using IronBarCode;

// Enable IronBarcode's built-in logging — set BEFORE any read/write calls
IronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.All;
IronSoftware.Logger.LogFilePath = "ironbarcode-debug.log";

// All subsequent operations will write diagnostic output to the log file
var options = new BarcodeReaderOptions
{
    Speed = ReadingSpeed.Detailed,
    ExpectBarcodeTypes = BarcodeEncoding.All
};

BarcodeResults results = BarcodeReader.Read("problem-scan.tiff", options);
Console.WriteLine($"Read complete. Results: {results.Count}. See ironbarcode-debug.log for details.");
//:path=/static-assets/barcode/content-code-examples/how-to/detailed-error-messages/enable-logging.cs
using IronBarCode;

// Enable IronBarcode's built-in logging — set BEFORE any read/write calls
IronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.All;
IronSoftware.Logger.LogFilePath = "ironbarcode-debug.log";

// All subsequent operations will write diagnostic output to the log file
var options = new BarcodeReaderOptions
{
    Speed = ReadingSpeed.Detailed,
    ExpectBarcodeTypes = BarcodeEncoding.All
};

BarcodeResults results = BarcodeReader.Read("problem-scan.tiff", options);
Console.WriteLine($"Read complete. Results: {results.Count}. See ironbarcode-debug.log for details.");
Imports IronBarCode

' Enable IronBarcode's built-in logging — set BEFORE any read/write calls
IronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.All
IronSoftware.Logger.LogFilePath = "ironbarcode-debug.log"

' All subsequent operations will write diagnostic output to the log file
Dim options As New BarcodeReaderOptions With {
    .Speed = ReadingSpeed.Detailed,
    .ExpectBarcodeTypes = BarcodeEncoding.All
}

Dim results As BarcodeResults = BarcodeReader.Read("problem-scan.tiff", options)
Console.WriteLine($"Read complete. Results: {results.Count}. See ironbarcode-debug.log for details.")
$vbLabelText   $csharpLabel

IronSoftware.Logger.LoggingModes.All captures both debug output and file-level logging. The log file records internal processing steps — image pre-processing stages, format detection attempts, and native interop calls — that are not visible through the public API alone.

For production pipelines that already use a structured logging framework (Serilog, NLog, Microsoft.Extensions.Logging), we recommend wrapping IronBarcode operations in a middleware layer that writes structured JSON entries alongside the built-in log file. The built-in logger writes plain-text diagnostics useful for support escalation; the structured wrapper gives us queryable fields in our observability stack.

//:path=/static-assets/barcode/content-code-examples/how-to/detailed-error-messages/structured-wrapper.cs
using IronBarCode;
using System.Diagnostics;

// Lightweight wrapper for structured observability
BarcodeResults ReadWithDiagnostics(string filePath, BarcodeReaderOptions options)
{
    var sw = Stopwatch.StartNew();
    try
    {
        BarcodeResults results = BarcodeReader.Read(filePath, options);
        sw.Stop();
        Console.WriteLine($"{{\"file\":\"{filePath}\",\"status\":\"ok\","
            + $"\"count\":{results.Count},\"elapsed_ms\":{sw.ElapsedMilliseconds}}}");
        return results;
    }
    catch (Exception ex)
    {
        sw.Stop();
        Console.Error.WriteLine($"{{\"file\":\"{filePath}\",\"status\":\"error\","
            + $"\"exception\":\"{ex.GetType().Name}\",\"message\":\"{ex.Message}\","
            + $"\"elapsed_ms\":{sw.ElapsedMilliseconds}}}");
        throw;
    }
}
//:path=/static-assets/barcode/content-code-examples/how-to/detailed-error-messages/structured-wrapper.cs
using IronBarCode;
using System.Diagnostics;

// Lightweight wrapper for structured observability
BarcodeResults ReadWithDiagnostics(string filePath, BarcodeReaderOptions options)
{
    var sw = Stopwatch.StartNew();
    try
    {
        BarcodeResults results = BarcodeReader.Read(filePath, options);
        sw.Stop();
        Console.WriteLine($"{{\"file\":\"{filePath}\",\"status\":\"ok\","
            + $"\"count\":{results.Count},\"elapsed_ms\":{sw.ElapsedMilliseconds}}}");
        return results;
    }
    catch (Exception ex)
    {
        sw.Stop();
        Console.Error.WriteLine($"{{\"file\":\"{filePath}\",\"status\":\"error\","
            + $"\"exception\":\"{ex.GetType().Name}\",\"message\":\"{ex.Message}\","
            + $"\"elapsed_ms\":{sw.ElapsedMilliseconds}}}");
        throw;
    }
}
Imports IronBarCode
Imports System.Diagnostics

' Lightweight wrapper for structured observability
Function ReadWithDiagnostics(filePath As String, options As BarcodeReaderOptions) As BarcodeResults
    Dim sw = Stopwatch.StartNew()
    Try
        Dim results As BarcodeResults = BarcodeReader.Read(filePath, options)
        sw.Stop()
        Console.WriteLine($"{{""file"":""{filePath}"",""status"":""ok"",""count"":{results.Count},""elapsed_ms"":{sw.ElapsedMilliseconds}}}")
        Return results
    Catch ex As Exception
        sw.Stop()
        Console.Error.WriteLine($"{{""file"":""{filePath}"",""status"":""error"",""exception"":""{ex.GetType().Name}"",""message"":""{ex.Message}"",""elapsed_ms"":{sw.ElapsedMilliseconds}}}")
        Throw
    End Try
End Function
$vbLabelText   $csharpLabel

The structured output integrates directly with log aggregation tools — stdout piped to Fluentd, Datadog, or CloudWatch in a containerized deployment. The elapsed-time field surfaces performance regressions before they become SLA violations.


How to Debug Batch Barcode Processing?

We process N files by isolating each read in its own try-catch block, recording per-file outcomes, and producing an aggregate summary at the end. The pipeline continues through failures rather than aborting on the first error.

//:path=/static-assets/barcode/content-code-examples/how-to/detailed-error-messages/batch-processing.cs
using IronBarCode;
using IronBarCode.Exceptions;
using System.Diagnostics;

// Enable built-in logging for the entire batch run
IronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.All;
IronSoftware.Logger.LogFilePath = "batch-run.log";

string[] files = Directory.GetFiles("scans/", "*.*", SearchOption.TopDirectoryOnly);

var options = new BarcodeReaderOptions
{
    Speed = ReadingSpeed.Balanced,
    ExpectBarcodeTypes = BarcodeEncoding.Code128 | BarcodeEncoding.QRCode,
    ExpectMultipleBarcodes = true
};

int successCount = 0;
int failCount = 0;
int emptyCount = 0;
var errors = new List<(string File, string Error)>();
var sw = Stopwatch.StartNew();

foreach (string file in files)
{
    try
    {
        BarcodeResults results = BarcodeReader.Read(file, options);

        if (results == null || results.Count == 0)
        {
            emptyCount++;
            errors.Add((file, "No barcodes detected"));
            continue;
        }

        foreach (BarcodeResult result in results)
        {
            Console.WriteLine($"{Path.GetFileName(file)} | {result.BarcodeType} | {result.Value} | {result.Confidence}%");
        }
        successCount++;
    }
    catch (IronBarCodePdfPasswordException)
    {
        failCount++;
        errors.Add((file, "Password-protected PDF"));
    }
    catch (IronBarCodeFileException ex)
    {
        failCount++;
        errors.Add((file, $"File error: {ex.Message}"));
    }
    catch (IronBarCodeException ex)
    {
        failCount++;
        errors.Add((file, $"{ex.GetType().Name}: {ex.Message}"));
    }
    catch (Exception ex)
    {
        failCount++;
        errors.Add((file, $"Unexpected: {ex.GetType().Name}: {ex.Message}"));
    }
}

sw.Stop();

// Summary report
Console.WriteLine("\n--- Batch Summary ---");
Console.WriteLine($"Total files:    {files.Length}");
Console.WriteLine($"Success:        {successCount}");
Console.WriteLine($"Empty reads:    {emptyCount}");
Console.WriteLine($"Failures:       {failCount}");
Console.WriteLine($"Elapsed:        {sw.Elapsed.TotalSeconds:F1}s");

if (errors.Any())
{
    Console.WriteLine("\n--- Error Details ---");
    foreach (var (errorFile, errorMsg) in errors)
    {
        Console.Error.WriteLine($"  {Path.GetFileName(errorFile)}: {errorMsg}");
    }
}
//:path=/static-assets/barcode/content-code-examples/how-to/detailed-error-messages/batch-processing.cs
using IronBarCode;
using IronBarCode.Exceptions;
using System.Diagnostics;

// Enable built-in logging for the entire batch run
IronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.All;
IronSoftware.Logger.LogFilePath = "batch-run.log";

string[] files = Directory.GetFiles("scans/", "*.*", SearchOption.TopDirectoryOnly);

var options = new BarcodeReaderOptions
{
    Speed = ReadingSpeed.Balanced,
    ExpectBarcodeTypes = BarcodeEncoding.Code128 | BarcodeEncoding.QRCode,
    ExpectMultipleBarcodes = true
};

int successCount = 0;
int failCount = 0;
int emptyCount = 0;
var errors = new List<(string File, string Error)>();
var sw = Stopwatch.StartNew();

foreach (string file in files)
{
    try
    {
        BarcodeResults results = BarcodeReader.Read(file, options);

        if (results == null || results.Count == 0)
        {
            emptyCount++;
            errors.Add((file, "No barcodes detected"));
            continue;
        }

        foreach (BarcodeResult result in results)
        {
            Console.WriteLine($"{Path.GetFileName(file)} | {result.BarcodeType} | {result.Value} | {result.Confidence}%");
        }
        successCount++;
    }
    catch (IronBarCodePdfPasswordException)
    {
        failCount++;
        errors.Add((file, "Password-protected PDF"));
    }
    catch (IronBarCodeFileException ex)
    {
        failCount++;
        errors.Add((file, $"File error: {ex.Message}"));
    }
    catch (IronBarCodeException ex)
    {
        failCount++;
        errors.Add((file, $"{ex.GetType().Name}: {ex.Message}"));
    }
    catch (Exception ex)
    {
        failCount++;
        errors.Add((file, $"Unexpected: {ex.GetType().Name}: {ex.Message}"));
    }
}

sw.Stop();

// Summary report
Console.WriteLine("\n--- Batch Summary ---");
Console.WriteLine($"Total files:    {files.Length}");
Console.WriteLine($"Success:        {successCount}");
Console.WriteLine($"Empty reads:    {emptyCount}");
Console.WriteLine($"Failures:       {failCount}");
Console.WriteLine($"Elapsed:        {sw.Elapsed.TotalSeconds:F1}s");

if (errors.Any())
{
    Console.WriteLine("\n--- Error Details ---");
    foreach (var (errorFile, errorMsg) in errors)
    {
        Console.Error.WriteLine($"  {Path.GetFileName(errorFile)}: {errorMsg}");
    }
}
Imports IronBarCode
Imports IronBarCode.Exceptions
Imports System.Diagnostics
Imports System.IO

' Enable built-in logging for the entire batch run
IronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.All
IronSoftware.Logger.LogFilePath = "batch-run.log"

Dim files As String() = Directory.GetFiles("scans/", "*.*", SearchOption.TopDirectoryOnly)

Dim options As New BarcodeReaderOptions With {
    .Speed = ReadingSpeed.Balanced,
    .ExpectBarcodeTypes = BarcodeEncoding.Code128 Or BarcodeEncoding.QRCode,
    .ExpectMultipleBarcodes = True
}

Dim successCount As Integer = 0
Dim failCount As Integer = 0
Dim emptyCount As Integer = 0
Dim errors As New List(Of (File As String, Error As String))()
Dim sw As Stopwatch = Stopwatch.StartNew()

For Each file As String In files
    Try
        Dim results As BarcodeResults = BarcodeReader.Read(file, options)

        If results Is Nothing OrElse results.Count = 0 Then
            emptyCount += 1
            errors.Add((file, "No barcodes detected"))
            Continue For
        End If

        For Each result As BarcodeResult In results
            Console.WriteLine($"{Path.GetFileName(file)} | {result.BarcodeType} | {result.Value} | {result.Confidence}%")
        Next
        successCount += 1
    Catch ex As IronBarCodePdfPasswordException
        failCount += 1
        errors.Add((file, "Password-protected PDF"))
    Catch ex As IronBarCodeFileException
        failCount += 1
        errors.Add((file, $"File error: {ex.Message}"))
    Catch ex As IronBarCodeException
        failCount += 1
        errors.Add((file, $"{ex.GetType().Name}: {ex.Message}"))
    Catch ex As Exception
        failCount += 1
        errors.Add((file, $"Unexpected: {ex.GetType().Name}: {ex.Message}"))
    End Try
Next

sw.Stop()

' Summary report
Console.WriteLine(vbCrLf & "--- Batch Summary ---")
Console.WriteLine($"Total files:    {files.Length}")
Console.WriteLine($"Success:        {successCount}")
Console.WriteLine($"Empty reads:    {emptyCount}")
Console.WriteLine($"Failures:       {failCount}")
Console.WriteLine($"Elapsed:        {sw.Elapsed.TotalSeconds:F1}s")

If errors.Any() Then
    Console.WriteLine(vbCrLf & "--- Error Details ---")
    For Each errorDetail In errors
        Console.Error.WriteLine($"  {Path.GetFileName(errorDetail.File)}: {errorDetail.Error}")
    Next
End If
$vbLabelText   $csharpLabel

The pattern distinguishes three outcome categories: success (barcodes found and decoded), empty (file read successfully but no barcodes detected), and failure (exception thrown). This three-way split is critical because empty reads and hard failures require different remediation — empty reads may need broader format settings or image correction filters, while failures point to infrastructure issues (missing files, locked resources, missing native DLLs).

The errors list preserves per-file context for post-mortem analysis. In a CI/CD pipeline, we can parse this output to set exit codes — zero for all success, non-zero if failCount > 0 — or feed the error details into an alerting system.

For higher throughput, we can enable parallel processing by setting options.Multithreaded = true and adjusting options.MaxParallelThreads to match available CPU cores. The per-file isolation pattern remains the same; we wrap the parallel iteration in Parallel.ForEach with a thread-safe collection for the error list.


What Are My Next Steps?

We covered the IronBarcode exception hierarchy with 11 typed exceptions, diagnostic extraction from BarcodeResult properties, built-in logging via IronSoftware.Logger, and a production-ready batch processing pattern with per-file error isolation.

For further reading, explore these resources:

Get a free trial license to test every feature in a live environment, or view licensing options when the pipeline is ready for production.

Frequently Asked Questions

How can I handle errors in barcode operations using IronBarcode?

IronBarcode provides typed exceptions and built-in logging to efficiently manage and handle errors in barcode operations, ensuring your application runs smoothly.

What features does IronBarcode offer for debugging barcode issues?

IronBarcode includes diagnostic extraction and production-ready batch error isolation, which assist developers in identifying and resolving barcode-related issues efficiently.

Can IronBarcode log errors during barcode processing?

Yes, IronBarcode has built-in logging capabilities that allow developers to capture and log error details during barcode processing, facilitating easier debugging.

What are typed exceptions in IronBarcode?

Typed exceptions in IronBarcode are specific error types that provide detailed information about barcode operation issues, making it easier for developers to diagnose and fix problems.

How does IronBarcode assist with batch error isolation?

IronBarcode offers production-ready batch error isolation, which helps in separating erroneous barcode operations from successful ones, streamlining error management in batch processing.

Is there a way to extract diagnostics from barcode operations using IronBarcode?

Yes, IronBarcode provides diagnostic extraction tools that help developers gather detailed information about barcode operations, aiding in troubleshooting and error resolution.

Curtis Chau
Technical Writer

Curtis Chau holds a Bachelor’s degree in Computer Science (Carleton University) and specializes in front-end development with expertise in Node.js, TypeScript, JavaScript, and React. Passionate about crafting intuitive and aesthetically pleasing user interfaces, Curtis enjoys working with modern frameworks and creating well-structured, visually appealing manuals.

...

Read More
Ready to Get Started?
Nuget Downloads 2,094,439 | Version: 2026.3 just released
Still Scrolling Icon

Still Scrolling?

Want proof fast? PM > Install-Package BarCode
run a sample watch your string become a barcode.