Batilla,
I looked around for something simple to use as an example and decided to add the exception handling code to Miss Eneroth’s open-newer-version covertversion.exe. As you’ll see this is pretty straight forward and it works just fine.
Here’s the code
// An example of exception handling with _try and _except
// added to Eneroth's open-newer-version
// https://github.com/Eneroth3/open-newer-version/tree/master/cpp
#include <SketchUpAPI/common.h>
#include <SketchUpAPI/initialize.h>
#include <SketchUpAPI/model/model.h>
#include <unordered_map>
#include <string>// std::string, std::stoi
int copyfile(const char*, const char*, enum SUModelVersion);
// command line: convertversion.exe source target version_number
// - Source path
// - Target path
// - SketchUp version (without leading 20)
int main(int argc, char* argv[]) {
if (argc != 4) return 1;
const char* source = argv[1];
const char* target = argv[2];
int version_name = std::stoi(argv[3]);
// REVIEW: Must be a way to simply append number to "SUModelVersion_SU" string
// and get enum from its string name.
const std::unordered_map<int, SUModelVersion> versions = {
{3,SUModelVersion_SU3},
{4,SUModelVersion_SU4},
{5,SUModelVersion_SU5},
{6,SUModelVersion_SU6},
{7,SUModelVersion_SU7},
{8,SUModelVersion_SU8},
{13,SUModelVersion_SU2013},
{14,SUModelVersion_SU2014},
{15,SUModelVersion_SU2015},
{16,SUModelVersion_SU2016},
{17,SUModelVersion_SU2017},
{18,SUModelVersion_SU2018},
{19,SUModelVersion_SU2019},
{20,SUModelVersion_SU2020}
// When adding new version here, also update HIGHEST_SUPPORTED_SU_VERSION in open_newer.rb.
};
enum SUModelVersion version = versions.at(version_name);
int result = copyfile(source, target, version);
return result;
}
int copyfile(const char* source, const char* target, enum SUModelVersion version) {
SUModelRef model = SU_INVALID;
__try {
SUInitialize();
SUResult res = SUModelCreateFromFile(&model, source);
if (res != SU_ERROR_NONE) return 1;
SUModelSaveToFileWithVersion(model, target, version);
SUModelRelease(&model);
SUTerminate();
}
// EXCEPTION_EXECUTE_HANDLER will force handling of all exceptions. Probably not what you want.
// for more informrtion on inplementing the __except 'filter' expression, visit
// https://docs.microsoft.com/en-us/cpp/cpp/try-except-statement?view=vs-2019#example
// and https://docs.microsoft.com/en-us/cpp/cpp/writing-an-exception-filter?view=vs-2019
__except (puts("in filter"), EXCEPTION_EXECUTE_HANDLER) {
puts("in exception handler");
return 2; // your error code
}
return 0;
}