Created
November 21, 2016 00:52
-
-
Save pallas/f530b8c3381944ac259a10e73f5bac1e to your computer and use it in GitHub Desktop.
C++ macros for trying libc calls, throwing std::runtime_error on errno
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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