Error handling

Proper error handling is crucial for building robust applications. ItalaApi reports errors using mechanisms that are idiomatic to each supported programming language. In general, languages with exception handling (C++, .NET, Python) will throw exceptions for error conditions, while the C API uses error codes.

The following examples demonstrate the basic error handling pattern for each language by attempting an invalid operation: creating a second system instance before the first one has been disposed of.

ItalaApi for C++ uses the standard GenICam exception set. To handle errors, user’s code should be prepared to catch GenICam::GenericException or classes derived from it.

#include <ItalaApi/Itala.h>
#include <GenICam/GenICam.h> // For GenericException
#include <iostream>

// ...

Itala::ISystem* pSystemOne = Itala::CreateSystem();

try
{
  // Attempting to create a second system instance will throw an exception
  Itala::ISystem* pSystemTwo = Itala::CreateSystem();
}
catch (const GenICam::GenericException& e)
{
  std::cerr << "An error occurred: " << e.what() << std::endl;
}

pSystemOne->Dispose();
pSystemOne = nullptr;

The C API functions return an ItalaError code. A successful operation returns ItalaErrorSuccess. If any other value is returned, an error has occurred. Users can then use ERR_GetLastErrorMessage() to retrieve a detailed description of the error.

#include "ItalaApiC/ItalaC.h"
#include <stdio.h>

// ...

ItalaError error = ItalaErrorSuccess;

// A call to any ItalaApiC function that might fail
error = SYS_Initialize(); // First call succeeds

// Attempting to initialize a second time will fail
error = SYS_Initialize();

if (error != ItalaErrorSuccess)
{
  size_t messageSize = 256;
  char errorMessage[256];
  ERR_GetLastErrorMessage(errorMessage, &messageSize);

  printf("Error Code: %d - Message: %s\n", error, errorMessage);
}

// Clean up the first, successful initialization
SYS_Dispose();

ItalaApi for .NET uses a custom exception set that extends the standard .NET Exception class. Users can catch the base System.Exception or more specific exception types from the ItalaApi namespace for finer-grained error handling.

using Itala;
using System;

// ...

ISystem systemOne = SystemFactory.Create();

try
{
  // Attempting to create a second system instance will throw an exception
  ISystem systemTwo = SystemFactory.Create();
}
catch (Exception e)
{
  Console.WriteLine($"An error occurred: {e.Message}");
}
finally
{
  systemOne.Dispose();
}

ItalaApi for Python translates GenICam exceptions into Python exceptions. Users can catch these errors using a standard try...except block.

from itala import itala

# The 'with' statement ensures dispose() is called even if errors occur inside the block
with itala.create_system() as system_one:
  try:
    # Attempting to create a second system instance will raise an exception
    system_two = itala.create_system()
  except Exception as e:
    print(f"An error occurred: {e}")