Home > Software design >  C Exception to Exception-less
C Exception to Exception-less

Time:10-28

I am looking to compile some C code that makes heavy usage of exceptions into a wasm target. Unfortunately, most browsers don't have Webassembly Exception Handling turned on (I believe only Chrome supports it behind the flag chrome://flags#enable-webassembly), and there's a tremendous performance hit in how emscripten wraps exceptions into a javascript try/catch. We've noticed about a 2x performance hit when the flag is turned on or off.

I believe the short-answer to this is 'no', but I was wondering if there are known approaches to translate C code-with-exceptions to C code that doesn't use exceptions at all (not even in a parent wrapper) without manually translating it.

CodePudding user response:

I think that the exceptions in the browsers will be optimized with time. I also think that the exceptions MUST (RFC 2119) not be used for a base of a computation, but only for events that SHOULD NOT (RFC 2119) happen.

Clearly "should" is relative and varies from person to person (project to project), but a disk error is clearly an event that should not happen (except, in the case when your program works with broken disks, and a disk error is a normal event). When the performance is an issue, changing the code seems to be the best solution.

An automatic translation sounds better, but when I think how often the standards are changing 11, 17, 20... I do not think that such a translation system will be managing to keep up, because its use cases would not be that much (personal opinion), that it might not worth developing it in the first place.

Anyway, a quick solution would be to wrap each exported function in a new catch-friendly one, that catches the exceptions and turns them into return values (or stores this information into thread-local variables), distinguishable from the normal return value, if any. That way at least the exceptions would not propagate to the JS side.

CodePudding user response:

The only thing that Exceptions have in common with Return values is that it's a form of error handling, code-wise, they are entirely two different things.

Barring any existing infrastructure where you can disable exceptions such as #define BOOST_NO_EXCEPTIONS in Boost, and disabling exception support with a compiler flag like -fno-exceptions (which will also make std near impossibe to use).. The only way is to manually edit... However, it is possible to return an error object, or throw it, which can make it easier to gradually introduce return values.

  • Related