How do I skip the "finally" block in C # when the exception is raised?

-1

If the exception is generated, I want to know if there is a way to "skip" the execution of block finally . If there is no exception, finally executes normally. With goto did not work.

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Calculadora
{
    class Program
    {
        static void Main(string[] args)
        {
            double n1, n2, multiplicacao;
            try
            {
                Console.Write("Digite o primeiro numero.\n");
                n1 = double.Parse(Console.ReadLine());
                Console.Write("Digite o segundo numero.\n");
                n2 = double.Parse(Console.ReadLine());
                multiplicacao = n1 * n2;

                Console.WriteLine("\nResultado...\n");
                Console.WriteLine(n1+" * "+n2+" = " + multiplicacao);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Erro ao tentar fazer a conta.");
                goto pular;
            }
            finally
            {
                Console.WriteLine("\nO finally foi executado...");
            }
            pular:
            Console.WriteLine("\n\n O finally nao foi executou.");
        }
    }
}
    
asked by anonymous 25.06.2017 / 00:54

4 answers

3

Citing MSDN

  

Typically, instructions for a finally block are executed when the   control leaves a try statement. The transfer of control may   occur as a result of normal execution, the execution of a   instruction break , continue , goto or return , or the propagation of a   exception out of try statement.

     

Within a handled exception, it is guaranteed that the finally block will be executed.

You can use the Environment.FailFast() method to terminate the application immediately, causing the finally block is not executed.

However, skip the block finally and run the code the way you want it is not possible.

    
25.06.2017 / 01:14
6

It does not make any sense what you're after, finally, is for you to execute the necessary logics if the try block can or does not do its job.

For example

You open the connection with SQL and then during a query the connection drops, an exception will be generated, but giving you right or wrong you need to close the connection with SQL, then you put this logic in finally .

If you want to finally jump, just remove it.

    
25.06.2017 / 01:15
6

This code has several problems, some are errors, others are just a bad style question:

1 - This problem does not have to deal with exception. He needs to check the error and give due treatment. Use TryParse() and be happy without exceptions.

2 - If it were to use exception, put in Finally only what should always be executed. What should not be run if you raise an exception, put it away.

3 - If you catch an exception, do as specific as possible, only use Exception if you have a good justification.

4 - If you are not going to use the exception variable, do not use it.

5 - Just declare the variable where you are going to use it, do not make pre-statements that do not bring benefits.

6 - It is not the end of the world in this case, but avoid string concatenations and prefer interpolation of string .

7 - I made other almost cosmetic improvements.

using static System.Console;

namespace Calculadora {
    public class Program {
        public static void Main(string[] args) {
            WriteLine("Digite o primeiro numero.");
            if (!double.TryParse(ReadLine(), out var n1)) { //dá para fazer genérico
                WriteLine("Dado digitado inválido");
                return;
            }
            WriteLine("Digite o segundo numero.");
            if (!double.TryParse(ReadLine(), out var n2)) { //reaproveite e não é necessário
                WriteLine("Dado digitado inválido");
                return;
            }
            double multiplicacao = n1 * n2;
            WriteLine("Resultado...");
            WriteLine($"{n1} * {n2} = {multiplicacao}");
            WriteLine("Tudo foi executado...");
        }
    }
}

See running on .NET Fiddle .

This code requires C # 7, but with a little modification it can run in C # 6 and with little else it can run in all versions.

If you still want to insist on the exception and even to answer the question, you do not want to skip finally and there is no finally . The attempt completion mechanism is that the code should be executed in any case. If you want it to be skipped when you give the exception, then it should be outside of the try-catch-finally block. That simple. You can do:

using System;
using static System.Console;

namespace Calculadora {
    public class Program {
        public static void Main(string[] args) {
            try {
                WriteLine("Digite o primeiro numero.");
                double n1 = double.Parse(ReadLine());
                WriteLine("Digite o segundo numero.");
                double n2 = double.Parse(ReadLine());
                double multiplicacao = n1 * n2;
                WriteLine("Resultado...");
                WriteLine($"{n1} * {n2} = {multiplicacao}");
            } catch (Exception) { //só para efeitos de teste, caso contrário não capture Exception
                WriteLine("Erro ao tentar fazer a conta."); //na prática agora nunca acontecerá a exceção
                WriteLine("O finally nao foi executou.");
                return;
            }
            WriteLine("Tudo foi executado...");
        }
    }
}

See running on .NET Fiddle . And no Coding Ground . Also put it in GitHub for future reference .

Note that there is another exception occurring. I think it's something momentary in .NET Fiddle, anyway it shows how problematic it is to catch Exception , get what you do not expect.

I stress that all of this is wrong, stay with the first one.

If you want to terminate a program and it is not in Main() then in place of return you must use the Environment.Exit() ", unless you are in a WinForms application, you should use Application.Exit() . There are other variations for applications of other technologies (WPF, UWP, ASPNET, etc.), even if it is a test. There are cases that even other solutions are more appropriate.

In addition to the fact that the question does not say when to finish the application, it talks about skipping catch .

    
25.06.2017 / 09:55
4

The goal of the finally block is to run either after executing the try block, when after any block catch . There is no way to "skip it".

When we start some process in the try block , which needs to be terminated, such as connecting to the database or opening a file, we usually use the in> finally to terminate the process. We thus avoid putting the closing code in the try block and all catch blocks.

In the code presented in your question, there is no reason to have a finally block. So, just do not implement it.

    
25.06.2017 / 01:19