0

so I am trying to error handle my code and so far this is what I have:

date = GetDate(); 
if(date.throws_exception())
{
// would it be possible to make a condition for where you can say if date throws exception?
}

string GetDate()
{
    try
    {
        .
        . 
        .
        return date;
    }
    catch(Exception ex)
    {
        throw new Exception();
    }
}

What I am wondering is it would be possible for the if condition, can you say:

if(date throws exception)
quaabaam
  • 1,808
  • 1
  • 7
  • 15
  • 1
    Is there a reason you don't want to do those things in the catch-block? – Tobias Kildetoft Jun 23 '20 at 17:45
  • 1
    Yes, in a indirect way. Instead of `GetDate` return a string, return a Tuple `(bool exceptionThrown, string value)`, where the bool indicate if an exception has been thrown. You can do `if(date.exceptionThrown)` – Magnetron Jun 23 '20 at 17:47
  • Is there a reason you can't use the built in `DateTime.TryParse` method? – quaabaam Jun 23 '20 at 17:59
  • Are you trying to develop an error handling strategy? If so, you probably want to bubble up your errors and not create too many `result` objects to then check for errors. A link that may help your error handling strategy, if that's your intent with this question... https://stackoverflow.com/questions/14973642/how-using-try-catch-for-exception-handling-is-best-practice – quaabaam Jun 23 '20 at 18:01

1 Answers1

2

You could put the method call in a try catch block, or rewrite your method to return a result object, or a tuple indicating success and holding the value.

Example returning tuple indicating success:

(bool Success, string Value) GetDate()
{
    try
    {
        .
        .
        .
        return (true, date);
    }
    catch(Exception ex)
    {
        return (false, null);
    }
}

Use like:

var result = GetDate(); 
if (result.Success)
{
    // do something with result.Value
}
Jacob Huckins
  • 368
  • 2
  • 15
  • 1
    Similarly, and if you don't like Tuples, use the 'Try' prefix naming convention, like `bool TryGetDate(out string Value)`. Usage: `var success = TryGetDate(out string value); if (success) { Console.WriteLine(value); }` – Sean Skelly Jun 23 '20 at 18:42
  • Following from Sean's advice, if a `'Try'` method already exists, such as `int.TryParse()`, it will almost always be better to use that method than to catch the exceptions and handle them yourself. – Jacob Huckins Jun 23 '20 at 18:45
  • 1
    Personally, as I'm married, I attributed my old implementation of a `TryGetDate` method with `[Obsolete]`. But I hope everyone else's implementations don't throw exceptions. ;) – Sean Skelly Jun 23 '20 at 18:55