Skip to content

Instantly share code, notes, and snippets.

@pallas
Created November 21, 2016 00:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pallas/f530b8c3381944ac259a10e73f5bac1e to your computer and use it in GitHub Desktop.
Save pallas/f530b8c3381944ac259a10e73f5bac1e to your computer and use it in GitHub Desktop.
C++ macros for trying libc calls, throwing std::runtime_error on errno
#ifndef TRY_H
#define TRY_H
#include <cstdio>
#include <cstring>
#include <stdexcept>
#include <errno.h>
#define TRY(f, ...) ({ \
typeof (f(__VA_ARGS__)) _r = f(__VA_ARGS__); \
if (_r < 0) perror(#f), throw std::runtime_error(strerror(errno)); \
_r; \
})
#define TRY_ERR(e, f, ...) ({ \
typeof (f(__VA_ARGS__)) _r = f(__VA_ARGS__); \
if (_r < 0 && errno != e) perror(#f), throw std::runtime_error(strerror(errno)); \
_r; \
})
#define TRY_PTR(f, ...) ({ \
typeof (f(__VA_ARGS__)) _r = f(__VA_ARGS__); \
if (!_r) perror(#f), throw std::runtime_error(strerror(errno)); \
_r; \
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment