Hans Rudel
Hans Rudel

Reputation: 3611

Returning a bool and rethrowing an exception

Is it possible to return a bool and also rethrow an exception within the same method? Ive tried with the following code and it keeps saying that unreachable code is detected or that i cant exit the finally block.

public bool AccessToFile(string filePath)
{
    FileStream source = null;
    try
    {
        source = File.OpenRead(filePath);
        source.Close();
        return true;
    }
    catch (UnauthorizedAccessException e)
    {
        string unAuthorizedStatus = "User does not have sufficient access privileges to open the file: \n\r" + filePath;
        unAuthorizedStatus += e.Message;
        MessageBox.Show(unAuthorizedStatus, "Error Message:");
        throw;
    }
    catch (Exception e)
    {
        string generalStatus = null;

        if (filePath == null)
        {
            generalStatus = "General error: \n\r";
        }
        else
        {
            generalStatus = filePath + " failed. \n\r";
            generalStatus += e.Message;
        }

        MessageBox.Show(generalStatus, "Error Message:");
        throw;
    }
    finally
    {
        if (source != null)
        {
            source.Dispose();
        }
    }
}

Upvotes: 1

Views: 206

Answers (1)

Paddy
Paddy

Reputation: 33867

Once you throw an exception, processing in your current method finishes and the exception works up the call stack. Either handle your exceptions locally and then return your boolean, or throw them and let them bubble up and handle them at the front end.

Upvotes: 4

Related Questions