HasanRasulov

try_catch_throw.c

Mar 9th, 2021
775
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.99 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <setjmp.h>
  3. #include <string.h>
  4. #include <stdbool.h>
  5.  
  6. #define NULLSTRING 1
  7. #define EMPTYSTRING 2
  8.  
  9. jmp_buf buf;
  10. int exception_number;
  11.  
  12. #define TRY if ((exception_number = setjmp(buf)) == 0)
  13. #define CATCH(x) else if (exception_number == x)
  14. #define CATCHALL else
  15. #define THROW(ex) (longjmp(buf, ex))
  16.  
  17. _Bool palindrome(const char *str)
  18. {
  19.  
  20.     if (str == NULL)
  21.         THROW(NULLSTRING);
  22.  
  23.     size_t len = strlen(str);
  24.  
  25.     if (len == 0)
  26.         THROW(EMPTYSTRING);
  27.  
  28.     size_t i;
  29.     for (i = 0; i <= len / 2; i++)
  30.     {
  31.  
  32.         if (str[i] != str[len - i - 1])
  33.             return false;
  34.     }
  35.     return true;
  36. }
  37.  
  38. int main()
  39. {
  40.  
  41.     TRY
  42.     {
  43.         printf("%d", palindrome("saa"));
  44.     }
  45.     CATCH(NULLSTRING)
  46.     {
  47.         printf("%s", "NullString!!!\n");
  48.     }
  49.     CATCH(EMPTYSTRING)
  50.     {
  51.         printf("%s", "EmptyString!!!\n");
  52.     }
  53.     CATCHALL
  54.     {
  55.         printf("%s", "unrecognized exception!\n");
  56.     }
  57.  
  58.     return 0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment