错误捕获最佳方法

时间:2014-10-09 12:13:49

标签: c#

您好我正在尝试获取所有故障单的列表,但它表示并非所有代码路径都返回一个值。有没有人没有我做错了谢谢

public List<TroubleTicket> GetAllTroubleTickets()
{
    try
    {

        List<TroubleTicket> tickets = new List<TroubleTicket>();


        var q = _supportDeskEntities.TroubleTickets.ToList();
        return q;
    }

    catch (Exception ex)
    {


    }


}

5 个答案:

答案 0 :(得分:2)

如果捕获异常,则该函数不返回任何值。所以改变这个:

catch (Exception ex)
{
}

对此:

catch (Exception ex)
{
  return null;
}

或者如果你希望它在捕获异常时返回一个空列表,那么你可以这样做:

catch (Exception ex)
{
   return new List<TroubleTicket>(0);
}

如果我们正在采取最佳做法,那么我会说你应该记录异常,然后重新抛出它。像这样:

catch (Exception ex)
{
   //write to log
   throw ex;
}

答案 1 :(得分:1)

您需要从catch语句返回一个值(或在其中抛出另一个异常)。否则,该函数将返回null

你可以试试这个:

public List<TroubleTicket> GetAllTroubleTickets()
{
    try
    {

        List<TroubleTicket> tickets = new List<TroubleTicket>();


        var q = _supportDeskEntities.TroubleTickets.ToList();
        return q;
    }

     catch (Exception ex)
    {
       return new List<TroubleTicket>(); // This is just in case you want to ignore any exceptions

    }


}

catch (Exception ex)
    {
       throw new Exception("There was an error getting tickets"); // Probably not as good of a way as you lose the exception details

    }

答案 2 :(得分:1)

如果没有抛出异常,您只返回一个值。您必须从catch块内返回,或返回try / catch结构外部。

所以你可以在两个不同的地方返回:

public List<TroubleTicket> GetAllTroubleTickets()
{
    try
    {
        var q = _supportDeskEntities.TroubleTickets.ToList();
        return q;
    }
    catch (Exception ex)
    {
        // You can also return "new List<TroubleTicket>()" if null is an unacceptable return value
        return null;
    }
}

或保留一个返回值变量,并将其设置在两个不同的位置,并将其返回到一个位置:

public List<TroubleTicket> GetAllTroubleTickets()
{
    List<TroubleTicket> tickets;
    try
    {
        tickets = _supportDeskEntities.TroubleTickets.ToList();
    }
    catch (Exception ex)
    {
        // You can also use "new List<TroubleTicket>()" if null is an unacceptable return value
        tickets = null;
    }
    return tickets;
}

答案 3 :(得分:1)

如果发生异常并且您没有将列表分配给List<TroubleTicket> tickets而是分配给其他变量,则不会返回任何内容。你可以这样做:

public List<TroubleTicket> GetAllTroubleTickets()
{
    List<TroubleTicket> tickets = null;
    bool gotTickets = true;
    try{
        tickets = _supportDeskEntities.TroubleTickets.ToList();
    }
    catch (SpecificException ex){ 
        gotTickets = false;
    }
    catch (Exception ex){ // catches all other "unexpected" exceptions
        // log and/or...
        throw;
    }
    return gotTickets ? tickets : null;
}

但是你不应该捕获所有类型的异常,而只能捕获您期望的特定类型。您还应该记录所有其他类型的例外。

答案 4 :(得分:0)

你的拦截块没有返回任何东西。

public List<TroubleTicket> GetAllTroubleTickets()
{
    List<TroubleTicket> tickets =null;
    try
    {
        tickets = new List<TroubleTicket>();
        var q = _supportDeskEntities.TroubleTickets.ToList();
        return q;
    }

    catch (Exception ex)
    {
       //Log or handle your error
    }

    return tickets;
}