c語言捕捉異常

來源:互聯網
上載者:User

標籤:

閑暇之日閱讀lua源碼,發現原來C語言除goto之外的另一個處理異常的方法。既為setjump longjump兩個函數,setjump相當於try,longjump相當於catch。與goto不同的是,longjump是全域的,比goto的作用範圍更廣。下面貼出簡單用法:

#include <stdlib.h>

#include <setjmp.h>

jmp_buf jumper;

int fdf(int a, int b) {

    if (b == 0)

    { // can‘t divide by 0

        longjmp(jumper, -3);//跳到以jumper 所在的jmp point,進行處理,-3 相當於具體的exception code.

    }

    return a / b;

}

int main (int argc, char **argv)

{

    int jstatus = setjmp(jumper);//相當於java catch,如果發生 jumper 異常,那麼會跳回到這個jmp point

    if (jstatus == 0) {//第一次執行的時候是正確的setjmp return 0.

        int a = 1;

        int b = 0;

        printf("%d/%d", a, b);

        int result = fdf(a, b);

        printf("=%d\n", result);

    }

    else if (jstatus == -3)

        printf(" --> Error:divide by zero\n");

    else

        printf("Unhandled Error Case");

}

c語言捕捉異常

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.