I have a C# application..I continuously get a null reference exception..I manage to catch this exception and log it..But i doubt if this exception will affect the performance of my application..Please note that i am not trying to avoid the exception instead i need to know if this exception affects the performance of my application if it is continuously fired .
-
2If you are getting null exceptions it means your code needs to be fixed. – Security Hound Jun 15 '12 at 10:37
4 Answers
If you're getting a NullReferenceException
, you should fix it rather than catching it. You should only ever catch it if it occurs in code in a way that you cannot fix (e.g. a broken third party library). A NullReferenceException
always indicates a programming error somewhere.
As for performance - it depends on what you mean by "continuously". Exceptions can be horribly expensive if they're thrown when nothing's really wrong - they're fine when used properly. How many are you seeing per second, for example? Note that when running in a debugger, exceptions are often much more expensive than they would be when a debugger isn't attached.
As ever, when you're worried about performance, you should test the performance, so you can use hard data to make decisions.

- 1,421,763
- 867
- 9,128
- 9,194
Exceptions have been designed to alter performances to a minimum when they are not thrown : adding a try/catch block should have very limited impact to your application performances. Therefore, I'd recommand to add as many try/catch blocks as required to catch any exception IN THE RIGHT LEVEL.
However, throwing and catching an exception may be very expensive. Application has to switch contexts, dispose any element in using blocks... And that's why I agree with @Ramhound : you ought to fix the exception rather than catching it.

- 3,145
- 2
- 20
- 26