Advertisement
Guest User

Untitled

a guest
Feb 7th, 2016
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.00 KB | None | 0 0
  1. /*
  2.  
  3. $ g++ errno_exception.cc; ./a.out
  4. Tentando alocar memoria ...
  5. error code(12): Cannot allocate memory
  6. Tentando abrir um arquivo ...
  7. error code(2): No such file or directory
  8.  
  9. */
  10.  
  11. #include <iostream>
  12. #include <cstring>
  13.  
  14. #include <errno.h>
  15.  
  16. #include <sys/types.h>
  17. #include <sys/stat.h>
  18. #include <fcntl.h>
  19.  
  20. #include <stdlib.h>
  21.  
  22. class sys_err {
  23. public:
  24. inline int code(void){ return errno; };
  25. inline char * description(){ return strerror(errno); }
  26. };
  27.  
  28. std::ostream& operator << (std::ostream& o , class sys_err z){
  29. o << "error code(" << z.code() << "): " << z.description() << "\n";
  30. return o;
  31. }
  32.  
  33. int main(void){
  34.  
  35. try {
  36. std::cout << "Tentando alocar memoria ...\n";
  37.  
  38. char *z = (char *)malloc((size_t)-1);
  39. if(z == NULL){
  40. throw sys_err();
  41. }
  42.  
  43. free(z);
  44.  
  45. }
  46.  
  47. catch(sys_err& e){
  48. std::cerr << e;
  49. }
  50.  
  51. try {
  52. std::cout << "Tentando abrir um arquivo ...\n";
  53.  
  54. int fd = open("/a/b/c/d", O_RDONLY);
  55. if(fd == -1){
  56. throw sys_err();
  57. }
  58.  
  59. }
  60.  
  61. catch(sys_err& e){
  62. std::cerr << e;
  63. }
  64.  
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement