Erratic behaviour when raising exception from foreign code