Run program inside Try/Catch

Asked

Viewed 546 times

7

Working with Visual Studio, when an error occurs while the program is running the program hangs and you can’t see where the program crashed and only appeared that error screen.

To catch where these mistakes happen we use the try catch, so we can capture where and why the mistake happened.

One possibility to never have this problem is to put the entire program inside a try catch, but I know it’s not good practice.

class Program
{
    static void Main(string[] args)
    {
        try
        {
            //Todo o programa
        }
        catch (Exception ex)
        {
            //Capturar os erros
        }
    }
}

What are the problems or why not leave the entire program inside a try catch?

3 answers

6


How can you tell by reading the end of that Article, the two main arguments are performance and integrity.

Performance

The first and most obvious reason not to use a try/catch in the entire program is that, generate a exception is much more expensive than controlling the work flow of the program with if/else. In case no exception is made, the if/else actually makes the flow slower, incoming, if a single exception is thrown, the running time spent to treat this exception is equivalent to several blocks if/else.

Integrity

The second reason, a little less obvious, is that if you have done anything before the exception is launched, everything that happens until you arrive reach the exception is executed, which makes the execution of part of the code useless. Meanwhile, in the if/else those lines that would be useless are despised before being executed.

Other issues

Beyond these two problems, in that reply it still deals with the semantic issue. Exceptions are for exceptional cases, so should be used when you waiting that a mistake will happen there. While if/else should be used to control the flow of the programme, including making it more natural to read and maintain the code easier.

A good example of when we should use try/catch is when we are trying to upload a file, there may be faults unrelated to your program, such as for example the file no longer exists or some problem occurs in reading the storage drive, in such cases where success is expected and you there’s no way to predict the error is where the try/catch must be used.

  • 2

    Felipe Avelar. If they are used in cases we do not expect a mistake, how to know when to place? Is there an example of a situation where you always use Try/catch? I think this complements the answer as well. Thank you.

  • @Joaopaulo, see if the edition improved the response a little.

5

No. This is not the way to do it.

There is a problem of putting the entire program inside a Try catch block but I will not refer to them but show you the right way to do it.

It exists on the platform. NET a way to record a chunk of code that will be triggered whenever an exception is left untreated and reach the top of the excution stack without treatment.

The following code, extracted from a question in stackoverflow.com, exemplifies the use:

using System;

class Program {
    static void Main(string[] args) {
        AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;
        throw new Exception("Kaboom");
    }

    static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e) {
        Console.WriteLine(e.ExceptionObject.ToString());
        Console.WriteLine("Press Enter to continue");
        Console.ReadLine();
        Environment.Exit(1);
    }
}

The code you register will play the role of your clause catch of a Try which involves the application as a whole.

3

To prevent all code from being inside a Try/catch you must improve your tests to detect faults. Everything must be validated using good programming techniques.
Therefore data entries should be validated, system calls, function returns access rights to resources, etc...
Applying best practices can be of great help.
Some tools can be seen here : Code Coverage for C#/. NET

  • I agree that tests and validations are essential and practices of utmost importance, but not with saying that this eliminates the need for generic treatment bugs, since the most difficult mistakes to find are precisely the ones that are most hidden, in which case some exceptional treatment mechanisms would be needed.

Browser other questions tagged

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