0

I'm having difficulty properly controlling flow in a piece of my code. I have a function GetVoucherNumberAndApplyToDatabase() which calls a separate function, doPatientEncounterCreate(). If the inner function throws an exception I want the outer function to stop what it's doing there as it's contingent on the returned value returned.

Here is the code for some clarity:

    //outer function
    private int GetVoucherNumberAndApplyToDatabase(int Mode)
    {
        int ProviderID = 0;
        int PracticeMRNumber = 0;
        int VoucherNumber = 0;
        string EncounterD = DateTime.Now.ToString("MM\\/dd\\/yyyy");
        try
        {
            EncounterCreateResults = doPatientEncounterCreate(practiceID, PracticeMRNumber, ProviderID, ddlVisitType.SelectedValue, EncounterD);

            /*
            if (EncounterCreateResults.ErrorMessage.Length > 0)
            {
                throw Exception;
            }
            */

            ...

            //fails bc doPatientEncounterCreate threw exception
            ApplyVoucherNumberToBillingCharges(practiceID, ReasonCodeID);
        }
        catch (ReasonCodeException ex)
        {
            pnlError.Visible = true;
            lblErrorMessage.Text = ex.Message;
        }
        catch (Exception ex)
        {
            pnlError.Visible = true;
            lblErrorMessage.Text = "An error occurred attempting to call the API: " + ex.Message;  
        }

    }

    //inner function
    public static EncounterResults doPatientEncounterCreate(int PracticeID, int PatientID
                                                  , int ProviderID, string ReasonCodeID, string EncounterD)
    {
        try
        {
            DataTable ReasonCodeDT = getSingleReasonCode(PracticeID, ReasonCodeID);

            string strReasonCode = String.Empty;
            string strReasonDescription = String.Empty;
            string strDuration = String.Empty;
            string strActive = String.Empty;

            if (ReasonCodeDT.Rows.Count != 1)
            {
                string strPracticeID = PracticeID.ToString();
                string PracticeName = getSingleStringResultFromSQL("SELECT @result ...); 
                string RecordCount = ReasonCodeDT.Rows.Count.ToString();
                throw new ReasonCodeException("Database Returned " + RecordCount + " Records for ReasonCodeID " + ReasonCodeID + " for Practice " + PracticeName + " (" + strPracticeID + ")");
            }
            else
            {
                DataRow Row = ReasonCodeDT.Rows[0];
                strReasonCode = Row["ReasonCodeID"].ToString();
                strReasonDescription = Row["Description"].ToString();
                strDuration = Row["Duration"].ToString();
                strActive = Row["Active"].ToString().ToLower();
            }

            string strReasonID = @"""ReasonCode"": {""Code"": """ + strReasonCode + @""", ""Description"":""" + strReasonDescription + @"""" +
                                @", ""Duration"": " + strDuration + @", ""Active"": " + strActive + @"}, ";
        }
        /*
        catch (ReasonCodeException ex)
        {
            Results.ErrorMessage = ex.Message;
            return Results;
        }*/
        catch (Exception ex)
        {
            ErrorLog.LogError(ex, "doPatientEncounterCreate Failed.", Convert.ToInt32(au.UserID), "");
            Results.ErrorMessage = ex.ToString();
            return Results;
        }
    }

    //Custom Exception Class used in doPatientEncounterCreate
    class ReasonCodeException : Exception
    {
        public ReasonCodeException()
        {

        }

        public ReasonCodeException(string Message):
            base ()
        {
            ErrorLog.LogError(Message);
        }

    }

I've taken the advice of the second answer to this qustion: Exit all functions from code in inner function

However, even though I've moved my ReasonCodeException catch block to the outer function, when the code is run, a generic exception is thrown in the for the inner function doPatientEncounterCreate() and then the code continues in the oter function until an exception is throw because it is missing the value returned from the inner function.

Also, I can't follow the advice of the accepted answer to the above question because the inner function isn't a void function, I need the value returned.

Any help you can provide is greatly appreciated.

1
  • If it is generic exception that is causing the problem, why don't you rethrow the exception from the inner function. You are returning rather than throwing.
    – user6277510
    May 2, 2018 at 15:54

2 Answers 2

2

For what you are trying to accomplish, would it be acceptable for you to not have a try catch block in your doPatientEncounterCreate method at all?

This would allow the try catch block in your GetVoucherNumberAndApplyToDatabase method to catch any exceptions that occur in doPatientEncounterCreate.

If you need a try catch block within the inner method, then as binDebug suggested in the comment, it makes sense to me to do what you need to in the catch block and then rethrow so your outer method catches it.

To clarify what I mean by "rethrow", here's a reference to an example. And, here is a brief snippet example:

catch(Exception e)
{
    // do something
    throw;
}
4
  • 1
    do something would have to be meaningful in this context (i.e. handling this non-specific exception in some partial way that still requires another handler farther up the call chain). May 2, 2018 at 18:25
  • @egnomerator When I follow your first suggestion about having no catch blocks in the inner function, it works as expected. However when I try to rethrow from the outer function, I'm getting an error for the doPatientEncounterCreate() method itself saying not all code paths return a value. Any idea why that might be. Any ideas on how to fix that?
    – W.Harr
    May 3, 2018 at 19:22
  • @W.Harr i didn't intend to suggest that you rethrow from the outer function, only the inner function - but perhaps you have a reason to do so, i just don't know what your requirements are. As to the error, if you try to look through that method following all code paths - for example a path into an if block - it sounds like there is a place where a return statement is expected but does not exist. that might be enough of a pointer, but if you need some help looking for that, could you post a new question with your updated method, and asking for help locating the source of the error? May 3, 2018 at 19:44
  • 1
    @egnomerator I realize the mistake I made. I thought I was to be rethrowing from the outside function so the inner function was still expecting a value to be returned. Thanks for your help.
    – W.Harr
    May 3, 2018 at 20:52
0

Right now, you have commented out the specific exception catch and only handling the generic one (which ALSO catches the specific one).

Now you are not re throwing the exception and only returning a valid response.

As per you need, you can process any specific exception as a proper logical chain in the child one by logging etc and then do a rethrow. Please note that there are 2 rethrow mechanism available, "throw" and "throw ex". Here you need to do a throw as it will preserve the stack trace without creating nested inner exception.

The other way is to not handle any exceptions in inner functions and let the higher level functions do the handling, often at a pipeline level. Ideally all known exception should be dealt at point of occurance and any unknown ones handled generically at global top level

2
  • I see the points you make. Could you expound on why it is better to handle exceptions where they occur, rather than at the top level?
    – W.Harr
    May 3, 2018 at 19:31
  • 1. Exception bubbling wraps the details in InnerException property, so if it comes from deep nested function, details become difficult to extract. 2) specific known conditions to be checked at source to prevent exception and avoid costly operation. 3) every bubbling is performance cost due to Stack wrapping involved. Hence only general exception which is unknown for underlying methods should handled globally and specific as locally.
    – NitinSingh
    May 4, 2018 at 3:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.