How to capture several exceptions with C#switch?

Asked

Viewed 63 times

0

I want to capture some exceptions using try-catch and switch. I made a few attempts, but it didn’t work. For example:

    try 
    {
       //tarefas...
    }
    catch (Exception ex)
    {
       switch ()
       {
         case PrimeiraExceção;
           tratar_a_exceção ...;
         break;

         case SegundaExceção;
           tratar_a_exceção ...;
         break;
           .
           .
           . 
       }
    }
  • makes several catch: Catch(ExceptionA){ } Catch(ExceptionB) { } ... and so on

  • Thanks Ricardo! There is no way to do with switch will?

  • vc can only have an Exception by Catch, no good do swith pq will always be 1. What can happen is an Exception return error codes, ai can switch the codes

  • Oh yes, I get it, blz. Thank you so much!! D

1 answer

2


switch does not serve to capture exception, the catch serves this purpose.

If you have one action for each captured exception then just use several catches. They function similarly to switch and will execute the block from which exception was launched.

If the following exceptions were more general than the previous ones then more than one catch can be executed since it may still have something to do in a broader context, otherwise it does not work, since if you treat first the more general the more specific will be dealt with together.

Can treat an exception among many also (only one is executed) if they have no direct relation, example:

} catch (SenhaNaoNumericaException) {
    WriteLine("A senha não é numérica");
} catch (SenhaMuitoPequenaException) {
    WriteLine("Senha não numérica.");
} catch (SenhaInicioAbaixoDe4Exception) {
    WriteLine("Não pode começar com número abaixo de 4.");
} catch (SenhaSemCaractereEspecialException) {
    WriteLine("Não foi encontrado nenhum caractere especial");
}

If you want to capture a more general exception and treat certain exception specifics differently then you need to use a slightly different mechanism. I’m going to play a answer given in Soen using automatic translator :D:

If you can upgrade your application to C# 6, you are in luck. This C# version has implemented exception filters. Then you can write this down:

catch (Exception ex) when (ex is CommunicationException || ex is SystemException) {
     //lidar com isso
}

Some people think that this code is the same as

catch (Exception ex) {
     if (ex is CommunicationException || ex is SystemException) {
         //lidar com isso
     }
     throw;
}

But it’s not. Actually, this is the only new C# 6 feature that cannot emulate in previous versions. First, a re-release means more overhead than skip the catch. Second, it’s not semantically equivalent. The new feature preserves the stack intact when you’re debugging your code. Without this feature, the dump memory is less useful or even useless.

An example that shows the difference.

Another example:

catch (Exception ex) when (ex is IOException || 
                           ex is UnauthorizedAccessException || 
                           ex is NotSupportedException || 
                           ex is SecurityException || 
                           ex is DirectoryNotFoundException || 
                           ex is PathTooLongException) {
    WriteLine("deu erro");
}

I put in the Github for future reference.

So fall in the same catch in all these exceptions but not in others. Some conditions may be used, need not be only exceptions, it is as if it were a if really, but it’s something better.

Read also: There is some drawback in always catching Exception and not something more specific?. And yet: How to best treat exceptions in Java?. In general people use exceptions mistakenly, I suggest you do a good search here before using them. You can start here.

  • Oops, wonderful!! Helped a lot, thank you very much @Maniero!

Browser other questions tagged

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