thesenate42069
thesenate42069

Reputation: 117

Is it possible to use a method throwing an exception in an if statement condition? c#

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)

Upvotes: 0

Views: 932

Answers (1)

Jacob Huckins
Jacob Huckins

Reputation: 378

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
}

Upvotes: 2

Related Questions