Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- $ g++ errno_exception.cc; ./a.out
- Tentando alocar memoria ...
- error code(12): Cannot allocate memory
- Tentando abrir um arquivo ...
- error code(2): No such file or directory
- */
- #include <iostream>
- #include <cstring>
- #include <errno.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <stdlib.h>
- class sys_err {
- public:
- inline int code(void){ return errno; };
- inline char * description(){ return strerror(errno); }
- };
- std::ostream& operator << (std::ostream& o , class sys_err z){
- o << "error code(" << z.code() << "): " << z.description() << "\n";
- return o;
- }
- int main(void){
- try {
- std::cout << "Tentando alocar memoria ...\n";
- char *z = (char *)malloc((size_t)-1);
- if(z == NULL){
- throw sys_err();
- }
- free(z);
- }
- catch(sys_err& e){
- std::cerr << e;
- }
- try {
- std::cout << "Tentando abrir um arquivo ...\n";
- int fd = open("/a/b/c/d", O_RDONLY);
- if(fd == -1){
- throw sys_err();
- }
- }
- catch(sys_err& e){
- std::cerr << e;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement