Block using and Exceptions

Asked

Viewed 110 times

1

Is there any way to report code errors in the block using as in the try we have the catch? Or using the using I’m stuck with a plethora of if, else if and else?

Supposing that the block using force you to create many conditions, which you prefer? try, catch e finally or using, if, else if e else?

  • 4

    The using serves one thing, the if and else to another and the try, catch and finally for a third thing. Technically, the question makes no sense. Semantically, when you say 'what you prefer?' automatically put the question - if it made sense - outside the scope of the site. Maybe we can help if you present a specific case in practice.

  • 1

    using nothing more than a block for scope restriction and Disposis, all the rest are instructions that have nothing to do with this.

  • 1

    Using creates a scope that is destroyed at the end, correct? But if I need to know whether a certain scope has been executed correctly or not, how using I would return if any exception were found?. try trial, catch reports and finally end. How to report exceptions in a block using?

  • Looking for links I found this and I think it’s duplicate: https://answall.com/q/165632/101

2 answers

4


The using really is a finally implicit and does not allow a catch. Some people even ask for it, but I doubt I ever will. The solution when you need to capture an exception that can occur in a block that works with a resource that must be dispensed at the end of its run is to use a try-catch-finally even.

Just careful because I see catch of exceptions being abused, in many cases would not need or even the exception should not be cast.

Another common problem is that people do not understand well what to do in the finally to call the method Dispose().

{
    var arq = new FileStream("arq.txt", FileMode.Create);
    try {
        //faz alguma coisa aqui
    } finally {
        if (arq != null) ((IDisposable)arq).Dispose();
    }
}

I put in the Github for future reference.

The if can be used in some contexts, depending on what you want to treat, if you use the if properly then the using will probably be used.

I gave a answer on the subject.

In C# 8 can do:

var using arq = new FileStream("arq.txt", FileMode.Create);

The block will be the current scope, so you wouldn’t need to create a new block like you needed before.

  • Exactly what I wanted to know. It is correct to state that this code using (var arq = new FileStream("arq.txt", FileMode.Create)) { //faz alguma coisa } has the same function as its code above?

  • 1

    I forgot the FileStream :) It is correct to state.

2

Hold on, let me explain.

using

is for when you will use an object and then discard it without storing information in memory.

using (StringBuilder sb = new StringBuilder()) {
    sb.AppendLine("Olá, mundo!");
}
// o StringBuilder sb não existe mais na memória

It is only used with objects that implement IDisposeable (disposable object). The block using does not implement any condition expression or exceptions.


Try

is used when you will capture Runtime errors within a block and will manipulate them.

int valor = 0;
try {
    // tente fazer isso
    valor = Convert.ToInt32("Isso não é um número");
} catch (Exception ex) {
    // se der erro, faça isso com o erro:
    Console.WriteLine("Não deu certo, pois " + ex.Message);
    valor = 10;
} finally {
    // no final, mesmo se der certo ou der erro,
    valor *= 2;
}

In the end, value will be 20, because inside the block will give an error to convert that string to a number. In the block catch, is assigned the value 10 for value, and on the block finally, is multiplied by two.

It is not recommended to use try, but only when you will do something that needs user manipulation.


if

this is the classic conditional, it will only perform what is inside the block if the expression is true:

if(1 + 1 == 2) {
     Console.WriteLine("Isso irá executar");
}
if(2 + 2 == 5) {
     Console.WriteLine("Isso não irá executar");
}

Of course obvious and constant values were used in the above example, but the block if accepts variables and constants, provided that the final value is Boolean.


Where to use all this?

You can combine the three above blocks, one inside the other, each performing a function. You just need to understand what each one does.

Give a read on documentation.

Browser other questions tagged

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