Return inside Try... catch does not work

Asked

Viewed 2,024 times

7

I did that method:

public int VerificaUltimaAnalise()
        {
            //Desenvolvimento
            WFExecutor vcmpExecutor = null;
            WFAnalise vcmpAnalise = null;
            Core vmpaCore = null;
            int vintCdTransacao = 0;
            int vintCdProxProcesso = 0;
            int vintCdAnalise = 0;

            try
            {
                //Instâncias e Inicializalções
                vcmpExecutor = new WFExecutor();
                vcmpAnalise = new WFAnalise();
                vmpaCore = (Core)Page.Master;

                //Desenvolvimento
                //vintCdTransacao = vcmpExecutor.ConsultarTransacao(Request.Path.Substring(Request.Path.LastIndexOf("/") + 1));

                vintCdProxProcesso = vcmpAnalise.ProximoProcessoAnalise(vintCdTransacao, int.Parse(hdfCdUsuario.Value), ref vintCdAnalise);

                return vintCdProxProcesso;
            }
            catch (Exception Ex)
            {
                Mensagem = (wucMensagens)Page.Master.FindControl("wucMasterMensagens");
                Mensagem.ExibirMensagem(wucMensagens.TipoAlerta.Erro, Ex.Source, Ex.Message, Ex.StackTrace);
            }
        }

And yet in design, gives me this mistake:

Not all code paths Return a value

This always happens when I try a Return inside a Try... catch block. What should I do to resolve this?

5 answers

11


The problem is the lack of a return. You must do it in catch also, so if there is an exception a return will always be executed. In the current form the return will only be executed if no failure occurs. This is inconsistent. According to the method signature it should always return something, even if a failure occurs.

The translation of the error message already illustrates the problem "not all paths return a value". Remember that the try-catch is a flow control, it deflects execution of code, it creates different execution paths according to events.

Probably you want to return nothing like this:

public int VerificaUltimaAnalise() {
    //Desenvolvimento
    WFExecutor vcmpExecutor = null;
    WFAnalise vcmpAnalise = null;
    Core vmpaCore = null;
    int vintCdTransacao = 0;
    int vintCdProxProcesso = 0;
    int vintCdAnalise = 0;
    try {
        //Instâncias e Inicializalções
        vcmpExecutor = new WFExecutor();
        vcmpAnalise = new WFAnalise();
        vmpaCore = (Core)Page.Master;
        //Desenvolvimento
        //vintCdTransacao = vcmpExecutor.ConsultarTransacao(Request.Path.Substring(Request.Path.LastIndexOf("/") + 1));
        vintCdProxProcesso = vcmpAnalise.ProximoProcessoAnalise(vintCdTransacao, int.Parse(hdfCdUsuario.Value), ref vintCdAnalise);
        return vintCdProxProcesso;
    } catch (Exception Ex) {
        Mensagem = (wucMensagens)Page.Master.FindControl("wucMasterMensagens");
        Mensagem.ExibirMensagem(wucMensagens.TipoAlerta.Erro, Ex.Source, Ex.Message, Ex.StackTrace);
        return 0;
    }
}

I put in the Github for future reference.

Just remembering that capture Exception is not usually a good idea in most cases.

Reading suggestion.

  • I wonder what error you have in your answer to deserve a -1.

5

This is because the code may never reach return in fact. Using your own code, for example:

        try
        {
            //Instâncias e Inicializalções
            vcmpExecutor = new WFExecutor();
            vcmpAnalise = new WFAnalise();
            vmpaCore = (Core)Page.Master;

            // Suponha que ocorra uma exceção na linha abaixo:
            vintCdProxProcesso = vcmpAnalise.ProximoProcessoAnalise(vintCdTransacao, int.Parse(hdfCdUsuario.Value), ref vintCdAnalise);

            return vintCdProxProcesso;
        }

I commented on a line in your code. Note that if there is an exception on this line, the program goes directly to catch, and your catch has no return instruction of anything:

        catch (Exception Ex)
        {
            Mensagem = (wucMensagens)Page.Master.FindControl("wucMasterMensagens");
            Mensagem.ExibirMensagem(wucMensagens.TipoAlerta.Erro, Ex.Source, Ex.Message, Ex.StackTrace);
        }

There are two ways to solve:

1. Placing a return in try and another in catch

For example:

    public int VerificaUltimaAnalise()
    {
        //Desenvolvimento
        WFExecutor vcmpExecutor = null;
        WFAnalise vcmpAnalise = null;
        Core vmpaCore = null;
        int vintCdTransacao = 0;
        int vintCdProxProcesso = 0;
        int vintCdAnalise = 0;

        try
        {
            //Instâncias e Inicializalções
            vcmpExecutor = new WFExecutor();
            vcmpAnalise = new WFAnalise();
            vmpaCore = (Core)Page.Master;

            //Desenvolvimento
            //vintCdTransacao = vcmpExecutor.ConsultarTransacao(Request.Path.Substring(Request.Path.LastIndexOf("/") + 1));

            vintCdProxProcesso = vcmpAnalise.ProximoProcessoAnalise(vintCdTransacao, int.Parse(hdfCdUsuario.Value), ref vintCdAnalise);

            return vintCdProxProcesso;
        }
        catch (Exception Ex)
        {
            Mensagem = (wucMensagens)Page.Master.FindControl("wucMasterMensagens");
            Mensagem.ExibirMensagem(wucMensagens.TipoAlerta.Erro, Ex.Source, Ex.Message, Ex.StackTrace);
            return 0;
        }
    }

2. Placing a return in the last execution line of the function or method

    public int VerificaUltimaAnalise()
    {
        //Desenvolvimento
        WFExecutor vcmpExecutor = null;
        WFAnalise vcmpAnalise = null;
        Core vmpaCore = null;
        int vintCdTransacao = 0;
        int vintCdProxProcesso = 0;
        int vintCdAnalise = 0;

        try
        {
            //Instâncias e Inicializalções
            vcmpExecutor = new WFExecutor();
            vcmpAnalise = new WFAnalise();
            vmpaCore = (Core)Page.Master;

            //Desenvolvimento
            //vintCdTransacao = vcmpExecutor.ConsultarTransacao(Request.Path.Substring(Request.Path.LastIndexOf("/") + 1));

            vintCdProxProcesso = vcmpAnalise.ProximoProcessoAnalise(vintCdTransacao, int.Parse(hdfCdUsuario.Value), ref vintCdAnalise);

            return vintCdProxProcesso;
        }
        catch (Exception Ex)
        {
            Mensagem = (wucMensagens)Page.Master.FindControl("wucMasterMensagens");
            Mensagem.ExibirMensagem(wucMensagens.TipoAlerta.Erro, Ex.Source, Ex.Message, Ex.StackTrace);
        }

        return 0;
    }

3

No getting into the merit of the pattern you chose to treat exceptions...

You cleared the exception on catch, then the method will always execute successfully.

Since it is a function, it requires a return. To resolve the build error, include a Return within the catch returning a default value.

-1

Insert a block Finally:

Finally
{
 return vintCdProxProcesso;
}

Like Finally, the code will always go through this section, in case of success or failure, as its variable was initialized with zero, then you will have the int return expected by the method.

I hope I’ve helped!!!

  • 2

    If it is strictly parsing syntax error as they did with the other negative answer, this too. In C#, the language of the question, there is no keyword Finally (note the capital).

  • It is not possible to return inside the body of a block finally.

-3

Puts a

finaly{
   return retorno
}

It makes you always return something even if it is null.

  • 3

    Your answer is wrong for missing the ; and a l in the finally but it’s a big exaggeration of who gave -1 for this, just warn to fix. I just didn’t fix it because I don’t like to alter content in response, although I’m sure your intention was to have it. Anyway the way put was missing a larger context. Maybe also negativated because it already has an equal answer. I think it’s unfair, too, but I don’t know what’s going on in everyone’s head.

  • It is not possible to return inside the body of a block finally.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.