Write custom function that will happens when throw happened [duplicate] - c#

This question already has answers here:
Custom exception handler
(5 answers)
Closed 5 years ago.
Is there a possibility to write a custom function that happened every time that throw of exeption happend without to write try and catch in c#?
UPDATE
I Want to get the exeption in my function and I'll check the exeption.
If I write try and catch, the catch will catch the exeption.
But I dont wont that there will be cases that the page will break Because there will not be try and catch.
In such cases I want to go to the base function.

Either some sort of product like Post Sharp (I think), or something a bit more invasive. Every call can be wrapped in an anonymous function that handles all exceptions for you. Then you can do whatever you want in that handler. Though, this requires you apply that style to all public methods that you'd want to deal with that issue.
Example:
public string GetSomeData() {
return Run(() => { ...some code... return "my result"; });
}
in the Run method, you can handle all try catch or whatever.

Related

Why doesn't the catch statement catch all the exceptions? [duplicate]

This question already has answers here:
How to handle exception raised in linq
(2 answers)
Closed 6 years ago.
I'm testing the method below and I realized that when I enter wrong file name, the error gets caught but when I don't have an element on the position specified, the error of IndexOutOfBounds crashes the program. The latter goes also for converting errors.
private static IEnumerable<Thing> Initialize()
{
try
{
string[] things = System.IO.File.ReadAllLines("things.txt");
return things.Select(_ => new Thing
{
Name = _.Split(';')[0],
Id = Convert.ToInt32(_.Split(';')[0])
});
}
catch(Exception exception)
{
Console.WriteLine(exception.Message);
return new List<Thing>();
}
}
Why doesn't some errors get handled despite the most general Exception type in the catch? Does it have to do with LINQ expression failing? If so, how do I force the catching, then?
This is because you return IEnumerable.
The lambda inside Select doesn't execute immediately, but only on accessing the enumerable (iterating items).
If you add call "ToArray" after "Select" then all items will be calculated and IndexOutRangeException will be catched in your catch block.
return things.Select(_ => new Thing
{
Name = _.Split(';')[0],
Id = Convert.ToInt32(_.Split(';')[0])
}).ToArray();
You are returning an IEnumerable<> which implies deferred execution.
So anything inside the lambda is actually executing later, outside the try/catch.
If you want to catch all errors, include a .ToList() , like
return things.Select(...).ToList();
I have experienced this a couple of years ago, and the explanation I found online is that it is because of unmanaged assemblies and code. Something that is out of the application domain. Mostly when you have a lower level (os level) operation

How can I throw exception inside a Generic Type Method?

Is there any way to throw or even safely return an exception inside a generic method?
my sample code looks like this:
public IEnumerable<T> findAverage<T>(float a, float b) where T : new ()
{
try
{
..... Do averaging instructions here......
}
catch(Exception e)
{
throw e
}
}
Now it seems good but the problem is whenever I create some test classes, I mean literally separate projects to test, the error redirects to the main source code of the created library. So I thought is there any way to return any exceptions without being redirected to the main library source?
any help || ideas || simple answers would be great. thanks!
Generally speaking, unless there is a clear need to do so, it is often better not to catch/re-throw exceptions at this low level of code, instead just let them bubble up to the front end (i.e. either your front end or your test code) for them to handle them as appropriate.
In this case, if you get an exception in your averaging code, what would a reasonable handling of this be? If you are not handling this, then don't catch it at all.

Exception Handling - What is the correct way to do it? [duplicate]

This question already has answers here:
General Exception Handling Strategy for .NET
(11 answers)
Closed 9 years ago.
I have been using exception handling for some time and have installed Resharper and now getting all sorts of messages saying I should and should be doing this. Anyway, it says I shouldn't be using try and catch blocks around my code. So where do I put them to catch exceptions? I have seen people looking for certain exceptions like File not found, but what about all the other errors or exceptions that are unique?
Here's an example of some exception handling it moans about:
try
{
var rnd = new Random();
var buffer = new byte[sizeof(UInt64)];
rnd.NextBytes(buffer);
}
catch (Exception)
{
throw;
}
Does anyone have links for best practices for exception handling that would keep re-sharper happy?
Only catch those exception which you can handle, like insertion of duplicate primary key, So that you can show the user a message to enter different values.
For other exception let them bubble up in your library and handle them in one place. Like Application_Error event in ASP.Net
As pointed out by others already, only use try/catch if you actually plan to do something about the exception inside the catch block - doing so keep in mind that there is actually no guarantee that the catch block will actually execute (e.g. a power failure).
See explanation that was given to me when I asked a quite similar question: when to use try/catch
If you only wish to diagnose/log an exception and don't do anything specific about it, you can use a global exception handler, i.e. AppDomain.UnhandledException - this way you can centralize handling.

Is there a situation when it's appropriate to use empty catch block? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Why are empty catch blocks a bad idea?
Is there any valid reason to ever ignore a caught exception
Do you know any situations when an empty catch block is not the absolute evil?
try
{
...
// What and When?
...
}
catch { }
There are a lot of questions on this, try to look at:
Why are empty catch blocks a bad idea?
From that post's accepted answer:
Usually empty try-catch is a bad idea because you are silently swallowing an error condition and then continuing execution. Occasionally this may be the right thing to do, but often it's a sign that a developer saw an exception, didn't know what to do about it, and so used an empty catch to silence the problem.
It's the programming equivalent of putting black tape over an engine warning light.
I would say you should at least be providing some sort of comment or logged message indicating that what you put in the try {} threw an exception and this is why you aren't doing anything.
Take a look at this, it basically breaks down the kind of exceptions you could encounter into four categories, none of which should be handled by an empty catch block.
Axiom:
Empty catch blocks are absolute evil
Don't try to find your way around this. Just by trying to find cases where they aren't absolute evil means you're wasting precious brain cycles. Don't try to find a pattern here, thinking "hmm, should I put an empty catch block here?"
If you stumble upon an empty catch block in somebody's code, you've just stumbled upon technical debt. Fix it. Even just by adding one logging statement inside an empty catch block, you'll make this world a better place.
I used it for some self-written libraries where i need some kind of bool TrySomething(out object) function or object TrySomething() where the underlying call doesn't provide any other mechanism as an exception. In this case i use an empty catch block and return false or null (depending on the function signature).
Example to prove empty catch block
public bool TrySomething(out object destination)
{
try
{
destination = DoSomething();
return true;
}
catch
{}
return false;
}

How to structure code with 2 methods, one after another, which throw the same two exceptions?

I have two methods, one called straight after another, which both throw the exact same 2 exceptions (IF an erroneous condition occurs, not stating that I'm getting exceptions).
For this, should I write seperate try and catch blocks with the one statement in each try block and catch both exceptions (Both of which I can handle as I checked MSDN class library reference and there is something I can do, eg, re-open SqlConnection or run a query and not a stored proc which does not exist). So code like this:
try
{
obj.Open();
}
catch (SqlException)
{
// Take action here.
}
catch (InvalidOperationException)
{
// Take action here.
}
And likewise for the other method I call straight after. This seems like a very messy way of coding. The other way is to code with the exception variable (that is ommited as I am using AOP to log the exception details, using a class-level attribute). Doing this, this could aid me in finding out which method caused an exception and then taking action accordingly. Is this the best approach or is there another best practise altogether?
I also assume that, as only these two methods are thrown, I do not need to catch Exception as that would be for an exception I cannot handle (causes way out of my control).
Thanks
You shouldn't catch an exception unless you can handle it in a sensible way and recover from the error. With that in mind, you should either choose not to catch these exceptions, or else you should catch them and do something useful and continue.
Assuming that you are trying to do the latter: handle the error and continue, does it really makes sense to do the same thing no matter which of the two statements fails? Assume you have this:
try {
f1();
f2();
} catch (FooException) {
// Recover from error and continue
}
f3();
In this case if f1() fails and you recover from the error, f2() will never be executed - it goes straight to f3(). Is that really what you want? Maybe it is sometimes... but not usually.
More likely, after the error from f1() you either want to quit completely with an error or to recover and then go on to execute f2(). If so then you would need two separate try/catch blocks.
If you're not interested in recovery but just logging the exceptions then the simplest way is to let them propagate and catch them at a higher level (but before your program crashes or becomes unusable) and log the message and stack trace. This ensures that you will log all exceptions and saves you having to insert try/catch and logging code in every method that could throw.
You're right that you shouldn't be catching Exception.
Generally you need as many catch clauses as you have different recovery approaches. If the recovery behavior is different for these two methods, I see nothing wrong with using a try/catch for each.
Especially consider whether you'd run the second method after successfully recovering the first. If so, you definitely don't want to put the second method in the same try block where it will be skipped by the exception.
You could create a method that accepts an Action parameter:
void trySomething(Action mightThrow)
{
try
{
mightThrow();
}
catch(SqlException)
{
}
catch(InvalidOperationException)
{
}
}
Then you can get the name of the method that threw by mightThrow.Method.Name.

Categories

Resources