如何重新抛出异常并在c#中返回一个值?

时间:2011-01-31 03:20:54

标签: c# exception

鉴于以下代码,如果抛出异常,如何返回一些值(DateTime.Now.ToString())?

public string DateToString(int year, int month, int day)
{
    try
    {
        DateTime datetime = new DateTime(year, month, day);
        return datetime.ToString();
    }
    catch (Exception)
    {
        //log error and rethrow
        throw;
    }
}

5 个答案:

答案 0 :(得分:12)

当您抛出异常时,您的方法会立即结束 也无法返回值。

当您调用抛出异常的方法时,控件将立即转移到catch块 您将无法观察或使用(不存在的)返回值。

你应该重新考虑你的设计。

答案 1 :(得分:3)

我认为你的问题措辞错误。看起来你只想要在异常时返回一个默认值。因此

public string DateToString(int year, int month, int day)
{
    try
    {
        DateTime datetime = new DateTime(year, month, day);
        return datetime.ToString();
    }
    catch (Exception exObj)
    {
        //log error
        LogMyError(exObj);
        return DateTime.Now.ToString();
    }
}

答案 2 :(得分:2)

我建议你这样做:

    bool IsValidDateTime(int year, int month, int day, out DateTime result)
    {
        try
        {
            result = new DateTime(year, month, day);
            return true;
        }
        catch (System.Exception ex)
        {
            result = DateTime.Now; // assign a value
            return false;
        }
    }

如果你想要一个字符串,只需确保返回值为true并调用

 result.ToString();

答案 3 :(得分:1)

考虑实际抛出异常的内容。如果你的函数返回一个值,可能你想在某个地方使用,对吗?

像:

// Will a value be assigned to dateString, or will an exception be thrown?
string dateString = DateToString(2011, 2, 29);

如果您希望DateToString 返回上述例外情况中的值,那么您希望将该值分配给dateString,对吗?但那么你想用例外做什么呢?要么你要继续,要么不继续;你无法双管齐下。

答案 4 :(得分:1)

编辑:cyberkiwi比我更好地掌握了这个问题,但我会把它作为阅读的坏榜样;)


您始终可以定义自己的异常类:

[Serializable()]
public class OwnException : System.Exception
{
    public readonly MaybeDateTime;

    ...
    public OwnException (string message, System.Exception inner) :  base(message, inner) { maybe = null; }
    public OwnException (string message, System.Exception inner, DateTime maybe) :  base(message, inner) { MaybeDateTime = maybe; }
}

并抛出一个(指定 datetime )。

你必须在try-catch-block之外转移 DateTime datetime -declaration,在你的例子中SLaks是正确的:它没有意义。如果return-Statement抛出捕获的异常, datetime 只能保存有意义的东西。在其他情况下,可能会有一些有用的应用程序。

编辑:使用字符串可以完成相同的操作,但是如果返回当前时间以便以一种好的方式解决情况,那么将其重新抛出为异常会有点愚蠢。如上所述,没有正确阅读。