Skip to content

C++ does not catch exceptions when used with Haskell-main and linked by ghc

Consider the C++ program

// Main_cc.cc
#include <iostream>
#include <exception>
extern "C" {
int func() {
  try {
    throw std::runtime_error("THIS FAILS!");
  } catch(const std::runtime_error &c) {
    std::cerr << c.what();
  }
  return 0;
}
}

and the Haskell program

-- Main.hs
module Main where
import Foreign.C.Types
foreign import ccall func :: IO CInt
main :: IO ()
main = print =<< func

When compiled with

ghc --make Main.hs Main_cc.cc -lstdc++

and being run on mac os x 10.11.3 the result is

libc++abi.dylib: terminating with uncaught exception of type std::runtime_error: THIS FAILS!
Abort trap: 6

and not (as it should be):

THIS FAILS!0

When compiled in a similar way under windows some c++ exceptions of a larger project are not caught as well. However, these were hard to track down and I was unable to construct a simple example like the one above.

As a workaround one can

  • write a main() function in c++ and call from there into Haskell,
  • compile the Haskell-Module with the options "-c -no-hs-main", and
  • link the application using g++ (not ghc!).

When being compiled / linked this way, all c++ exceptions are being caught in mac os x as well as under windows.

Trac metadata
Trac field Value
Version 7.10.3
Type Bug
TypeOfFailure OtherFailure
Priority normal
Resolution Unresolved
Component Runtime System
Test case
Differential revisions
BlockedBy
Related
Blocking
CC pl, simonmar
Operating system Unknown/Multiple
Architecture
To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information