Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rethrow an exception and return a value in c#?

Tags:

c#

exception

Given the following code, how can I return some value (DateTime.Now.ToString()) if the exception is thrown?

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;
    }
}
like image 241
IanM Avatar asked Jan 31 '11 03:01

IanM


1 Answers

When you throw an exception, your method ends immediately.
There is no way to return a value too.

When you call a method which throws an exception, control will immediately transfer to a catch block.
You won't get any chance to observe or use the (nonexistent-) return value.

You should rethink your design.

like image 126
SLaks Avatar answered Sep 27 '22 23:09

SLaks