Try Catch Exception

Synopsis

Try and catch an itk::ExceptionObject. The exception is printed to console output. This can provide more information when a program crashes, including where the exception occurred and its description. Exceptions in ITK are usually only thrown during calls to ->Update(), so only the ->Update() call is added to the try block.

Results

ExceptionObject caught !

itk::ImageFileReaderException (0x20cece0)
Location: "void itk::ImageFileReader<TOutputImage, ConvertPixelTraits>::GenerateOutputInformation() [with TOutputImage = itk::Image<double, 2u>, ConvertPixelTraits = itk::DefaultConvertPixelTraits<double>]"
File: /path/to/ITK/Modules/IO/ImageBase/include/itkImageFileReader.hxx
Line: 143
Description:  Could not create IO object for file nofile.png
The file doesn't exist.
Filename = nofile.png

Code

C++

#include "itkImage.h"
#include "itkImageFileReader.h"

int
main(int, char *[])
{
  constexpr unsigned int Dimension = 2;
  using PixelType = double;

  using ImageType = itk::Image<PixelType, Dimension>;
  using ReaderType = itk::ImageFileReader<ImageType>;

  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName("nofile.png");

  try
  {
    reader->Update();
  }
  catch (itk::ExceptionObject & err)
  {
    std::cerr << "ExceptionObject caught !" << std::endl;
    std::cerr << err << std::endl;

    // Since the goal of the example is to catch the exception,
    // we declare this a success.
    return EXIT_SUCCESS;
  }

  // Since the goal of the example is to catch the exception,
  // the example fails if it is not caught.
  return EXIT_FAILURE;
}

Classes demonstrated