Cè¨èªã§Javaã¨åçç¨åº¦ã®ä¾å¤å¦çããã£ã¦ã¿ã
ãåãã®éãCè¨èªã«ã¯ä¾å¤å¦çã¨ããç«æ´¾ãªãã®ã¯æè¼ããã¦ããªãã
ããã§ãCè¨èªã§setjmpã¨ããé¢æ°ã使ã£ã¦Javaã¨åçã®ä¾å¤å¦çããã£ã¦ã¿ãã
Javaã¨Cã§my_divã¨ããé¢æ°ãä½ã£ã¦ä¾å¤å¦çããã
- intåã®å¼æ°ã2ã¤æã¤é¢æ°ï¼ã¡ã½ããï¼ãå®ç¾©ãã¦å²ãç®ããçµæãintã§è¿ã
- a / bã®ã¨ãbãã¼ãã®å ´åã«ã¼ãé¤ç®ä¾å¤ãèµ·ãã
- a / bã®ã¨ãaãã¼ãã®å ´åã«ãã®ä»ã®ä¾å¤ãèµ·ãã
Javaã§ã¯ã»ã»
bãã¼ãã®æã¯ç¹ã«ä¾å¤å¤å®ãããå¿ è¦ããªããåæã«ã¼ãé¤ç®ä¾å¤ã«ãªãã®ã§æ¬¡ã®ããã«ãªãã
class Longjump { public static void main(String[] args) { int x, y, ans; if (args.length != 2) { System.err.println("Usage: java Longjump X Y"); System.exit(1); } x = Integer.parseInt(args[0]); y = Integer.parseInt(args[1]); try { ans = my_div(x, y); System.out.println(x + " / " + y + " = " + ans); } catch (ArithmeticException e) { System.err.println("Zero div exception!"); } catch (Exception e) { System.err.println("Exception!"); } } private static int my_div(int a, int b) throws Exception, ArithmeticException { if (a == 0) { throw new Exception(); } return a / b; } }
çµæ
$ java Longjump 10 3
10 / 3 = 3$ java Longjump 10 0
Zero div exception!$ java Longjump 0 3
Exception!
Cè¨èªã§ã¯ã»ã»
setjmpã¨longjmpã®ã³ã³ãã§ãã®ããã«ãªã
#include <stdio.h> #include <setjmp.h> enum { ZERO_DIV_EXCEPTION = 1, OTHER_EXCEPTION = 2, }; jmp_buf env; int my_div(int a, int b) { /* throws ZERO_DIV_EXCEPTION */ if (a == 0) { /* throw OTHER_EXCEPTION;*/ longjmp(env, OTHER_EXCEPTION); } if (b == 0) { /* throw ZERO_DIV_EXCEPTION;*/ longjmp(env, ZERO_DIV_EXCEPTION); } return a / b; } int main(int argc, char *argv[]) { int x, y, ans, e; if (argc != 3) { fprintf(stderr, "Usage: ./longjmp X Y\n"); return 1; } x = atoi(argv[1]); y = atoi(argv[2]); if ((e = setjmp(env)) == 0) { /* try */ ans = my_div(x, y); printf("%d / %d = %d\n", x, y, ans); } else if (e == ZERO_DIV_EXCEPTION) { /* catch (ZERO_DIV_EXCEPTION e) */ fprintf(stderr, "Zero div exception!\n"); } else { /* catch (Exception e) */ fprintf(stderr, "Exception!\n"); } return 0; }
çµæ
$ ./longjmp 10 3
10 / 3 = 3$ ./longjmp 10 0
Zero div exception!$ ./longjmp 0 3
Exception!
ãããã¾ã£ããåãçµæã«ãªã£ãã
ããã綺éºï¼ï¼
ä»çµã¿
setjmp
setjmpã¯å¼ã°ããæã®å®è¡ã³ã³ããã¹ãï¼ããã°ã©ã ã«ã¦ã³ã¿ï¼CP)ãå«ãæ±ç¨ã¬ã¸ã¹ã¿ã®å¤ãªã©ï¼ãjmp_bufã«æ ¼ç´ãããã
â»longjmpãå¼ã°ããå¾ä»¥å¤ã¯ãå¿
ã0ãè¿å´ãããã
longjmp
longjmpã¯ç¬¬ä¸å¼æ°ã«æå®ããjmp_bufã«æ ¼ç´ãããå®è¡ã³ã³ããã¹ãã®ç¶æ
ã¸é·ç§»ããããã«ãªã£ã¦ããã
â»ç¬¬äºå¼æ°ã¯ãsetjmpã¸é·ç§»ããæã®setjmpã®æ»ãå¤ã¨ãªãï¼ç¬¬äºå¼æ°ã«0ãæå®ããå ´åã¯å¼·å¶çã«1ã«å¤æ´ãããï¼
以ä¸ã®ä»çµã¿ã«ãããé¢æ°å¼ã³åºããè¡ã£ã¦ããå ´åã§ãsetjmpãå¼ã°ããä½ç½®ã¾ã§ä½äºããªãæ»ã£ã¦ããã
注ï¼
Javaã§ãåãã ããä¾å¤ãèµ·ããã¾ã§ã«å¤æ´ãããã¡ã¢ãªå
容
ä¾ãã°
if ((e = setjmp(env)) == 0) { /* try */ ans = 999; ans = my_div(x, y); printf("%d / %d = %d\n", x, y, ans); }
ã¨ãªãå ´åã«ã¯ãmy_divã§ä¾å¤ãèµ·ãã£ã¦ãansã®å¤ã¯999ã¨ãªã£ãã¾ã¾ã§
ã¡ã¢ãªã®å¤ã¾ã§æ»ããªãã¨ããäºã注æãã¦ãããããã
ã¾ã¨ã
setjmpã¯Rubyçã®è¨èªå¦çç³»ã§ä¾å¤ãå®ç¾ããããçã«ã使ç¨ããã¦ãããã¨ã¦ã使ããææ³ã§ããã
ãã²ãèªåãå«ãã¦è¦ãã¦ãããã1æã ã
ä»ã©ããªæã«ä½¿ããããã¨ãå¤ãã®ã ãããï¼