返回在try catch中创建的对象

时间:2014-01-24 02:11:15

标签: c# oop

执行以下操作并返回对象或null的最佳/正确方法是什么?

如果我在try / catch子句中声明返回Dictionary对象,它可能不会返回一个对象并因此而生成编译错误。但它应该至少返回一些东西,比如null?

public static Dictionary<string,string> myFunction()
{
    try {
        ...
        Dictionary<string,string> dict = new Dictionary();
    }

    catch {
        ...
    }

    return dict;
}

我是否只是在try / catch之外实例化返回的对象,并在调用程序中测试返回的值/长度?

4 个答案:

答案 0 :(得分:7)

public static Dictionary<string, string> myFunction()
{
    Dictionary<string, string> dict = null;
    try
    {
        dict = new Dictionary<string, string>();
    }
    catch
    {

    }

    return dict;
}

答案 1 :(得分:4)

public static Dictionary<string, string> myFunction()
{
    try
    {
        Dictionary<string, string> dict;

        dict = new Dictionary<string, string>();

        // do something with dict

        return dict;
    }
    catch (Exception ex)
    {
        // handle ex
    }

    return null;
}

答案 2 :(得分:1)

返回Dictionary块的try结束,从null返回catch。每次调用此函数时,请检查返回值。如果它为null,则这意味着发生了一件坏事。

如果您想在Dictionary区块内定义try,那么它完全确定,实际上它更好:

try 
{
    Dictionary<string,string> dict = new Dictionary();
    ...

    return dict;
}

catch 
{
    ...
    return null;
}

因为返回null Dictionary与直接返回null相同。如果您不需要在范围之外的变量,最好限制变量范围。

答案 3 :(得分:0)

正确移动try块外的字典声明。否则catch不能引用try块中定义的字典,因为它将超出范围。