Try catch finally用法

Try catch用法
無論是否出現異常,finally塊中的代碼都會執行;

Try中無異常:try---finally
Try中有異常:try---catch---finally
Try中無異常且try中有return:try---finally---return
Try中有異常且try中有return:try---catch---finally---return
Try中有異常且return在finally之後:try---catch---finally---錯誤異常已拋出,程序終止return不會執行
在try-catch-finally方法中,return可能出現的位置有四個,即try中、catch中、finally中、finally後,若同時出現,則編譯不會通過。最終會執行finally中的return,即finally中的return會覆蓋掉其他位置的return。
當finally中沒有return,但是finally中有改變return的返回值,那麼try或者catch中的return值會被finally修改嗎?不會,因爲在執行finally之前,return的值就已經被確定下來了。

簡單的使用案例:

using namespace std;
#include<iostream>                           
#include<stdlib.h>

double fuc(double x, double y)                       
{
    if(y==0)
    {
        throw y;                                    
    }
    return x/y;                                   
}

int main()
{
    double res;
    try                                           
    {
        res=fuc(2,3);
        cout<<"The result of x/y is : "<<res<<endl;
        res=fuc(4,0);                                
    }
    catch(double)                                    
    {
        cerr<<"error of dividing zero.\n";
        exit(1);                                   
    }

    try
    {
        throw 1;
    }
    catch(int)
    {
        printf("error");
    }

    try
    {
        int a[3] = {0,0,0};
        throw a;
    }
    catch(int[])
    {
        printf("error");
    }

    class MyException
    {
    public:
    protected:
        int code;
    };

    try
    {
        throw MyException();
    }
    catch(MyException)
    {
        printf("error");
    }
}

注:本文整理自網絡

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章