Ignore a specific Exception

Asked

Viewed 347 times

3

In my try-catch, I want to record the exception that occurred within an object (for historical effect, necessary for the business rule, since this section takes place in a processing via integration with external sources).

For that, I need to make sure catch that the exception was not from database or from my ORM, because if it would not give an exception within the exception... it would be a crash ugly and bam, system out of breath.

So that would be about it:

Try {
    //Cógido
}
catch (exception ex)
{
     //VERIFICAR SE NÃO É UMA EXCEÇÃO DE BD (MEU CASO ENTITY FRAMEWORK)
}

Is there such a possibility? How could I do this in a more general way possible?

2 answers

7


You are wanting to ignore the most important exception. There are a huge amount of exceptions that can occur in this case. Good systems log treat the problems that can occur in itself so Think about using one of them.

If you really want to do this you can filter the exceptions:

catch (Exception ex) when (!(ex is DbException) && !(ex is EntityException)) {
    //faz o que deseja aqui
}

But perhaps the right thing to do is to treat these exceptions first:

catch (ex DbException)) {
    //faz o que deseja aqui
} catch (ex EntityException) {
    //faz o que deseja aqui
} catch (Exception ex) {
    //faz o que deseja aqui
}

I hope you don’t have any other problems. Rare programmers who use exceptions in the right way.

I put in the Github for future reference.

  • Ball show @bigown. I already use Elmah. This case there was very specific and only to record processing effects (or defects) during integration. For history. It looks ugly but it was super conscious.

  • Important to remember that the is checks the entire inheritance structure of the object.

  • @jbueno but the intention to filter is just to get the whole hierarchy. I just missed the second example because I copied and pasted and forgot to take the is that no longer fits there :) Tidy.

6

Just know what kind of Exception who wants to ignore.

If you want to ignore one DbException, do the following

try 
{ 
}
catch (DbException ex)
{
    //ignorar
}

Browser other questions tagged

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