Advertisement
_takumi

exc

Jan 20th, 2023
899
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.93 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <setjmp.h>
  3. #include <stdlib.h>
  4.  
  5. typedef struct exception {
  6.     jmp_buf buf;
  7.     int code;
  8. } exception;
  9.  
  10. exception buffer[10];
  11. int stp = 0;
  12.  
  13. jmp_buf *try(int exception) {
  14.     buffer[stp].code = exception;
  15.     return &buffer[stp++].buf;
  16. }
  17.  
  18. void endtry() {
  19.     stp--;
  20. }
  21.  
  22. void throw(int exception) {
  23.     while (stp > 0 && buffer[stp - 1].code != exception) { stp--; }
  24.     stp--;
  25.     if (stp == -1) {
  26.         exit(13);
  27.     }
  28.     longjmp(buffer[stp].buf, buffer[stp].code);
  29. }
  30.  
  31. int main(int argc, char *argv[]) {
  32.     if (!setjmp(*try(42))) {
  33.         puts("level 1");
  34.         if (!setjmp(*try(1))) {
  35.             puts("level 2");
  36.             throw(42);
  37.             puts("this string is not displayed");
  38.             endtry();
  39.         } else {
  40.             puts("handle exception 1");
  41.         }
  42.         endtry();
  43.     } else {
  44.         puts("handle exception 42");
  45.     }
  46.     return 0;
  47. }
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement