Try Catch Finally总结

Try Catch Finally探究

1. try、catch、finally语句中,在如果try语句有return语句,则返回的是当前try中变量此时对应的值,此后对变量做任何的修改,都不影响try中return的返回值

public static int TryCatch(int i)
{
    int temp = 0;
    try
    {
        temp = i;
        return temp;
    }
    catch (Exception e)
    {
        return 0;
    }
    finally
    {
        temp=20;
    }
}
/*返回值为10*/

2 如果finally块中有return 语句,则返回try或catch中的返回语句就会被忽略,并且会忽悠掉try和catch里面抛出的异常

public static int TryCatch(int i)
{
    int temp = 0;
    try
    {
        temp = i;
        if(i==0)
        {
            throw new ArithmeticException();
        }
        return temp;
    }
    catch (Exception e)
    {
        return 1;
    }
    finally
    {
        temp=20;
        return temp;
    }
}
/*返回值为20*/

3 如果finally块中抛出异常,则整个try、catch、finally块中抛出异常。

使用try、catch、finally语句块中需要注意的是:

1 尽量在try或者catch中使用return语句。通过finally块中达到对try或者catch返回值修改是不可行的。
2 finally块中避免使用return语句,因为finally块中如果使用return语句,会显示的消化掉try、catch块中的异常信息,屏蔽了错误的发生,并且会把try里面的返回值消化掉。
3 finally块中避免再次抛出异常,否则整个包含try语句块的方法会抛出异常,并且会消化掉try、catch块中的异常。

原文地址:https://www.cnblogs.com/zengming/p/8506925.html