Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore Exception in C#

Tags:

Is there a better way to ignore an exception in C# than putting it up in a try catch block and doing nothing in catch? I find this syntax to be cumbersome. For a codeblock, can't I simply "tag" it in such a way so as runtime knows which exceptions to neglect?

like image 380
Sanrag Sood Avatar asked Feb 06 '11 12:02

Sanrag Sood


People also ask

Can exceptions be ignored?

It is extremely easy to ignore exceptions, you simply surround your exception throwing code with a try and empty catch block. Exceptions are thrown when exceptional circumstances are experienced so by ignoring exceptions we are opening ourselves up for problems.

How do I avoid exceptions?

Another way to avoid exceptions is to return null (or default) for extremely common error cases instead of throwing an exception. An extremely common error case can be considered normal flow of control. By returning null (or default) in these cases, you minimize the performance impact to an app.


2 Answers

I don't think there is a trick to avoid exception but you can use the following code snippet:

public void IgnoreExceptions(Action act) {    try    {       act.Invoke();    }    catch { } } 

Using the method looks like:

IgnoreExceptions(() => foo()); 

Another solution is to use AOP (Aspect Oriented Programming) - there's a tool called PostSharp which enables you to create an attribute that would catch all exceptions in specific assembly/class/method, which is closer to what you're looking for.

like image 114
Dror Helper Avatar answered Sep 28 '22 07:09

Dror Helper


You can do it with AOP. Postsharp for example will allow you to easily implement such an attribute which will skip particular exceptions in methods to which you applied such an attribute. Without AOP I do not see any good way to do that (if we assume that there is a good way to do such things ;) ).

With Postsharp you will be able to decorate your methods in this way:

[IgnoreExceptions(typeof(NullReferenceException), typeof(StackOverflowException))] void MyMethod() { ... } 
like image 33
Snowbear Avatar answered Sep 28 '22 05:09

Snowbear