Is there any possibility of occurrence of exception in catch block? If yes then how can I handle it in that situation?
-
4Yes. You can put try/catch within a catch block if you need to but that should be rare if at all. – Crowcoder Dec 18 '17 at 18:55
1 Answers
An exception can be thrown within a catch
block, but it's rare, or at least it should be. Obviously it depends on what you put in the catch
block.
Your best protection is to avoid extensive code within a catch
statement, and only include "safe" code that isn't reasonably likely to throw another exception.
Remember, nothing within the "normal" flow of your code should happen because of an exception, so in most cases you wouldn't have anything in your catch
except except logging or something else minor. If you've got a whole chunk of application code in your catch
, it probably shouldn't be there.
If you have to do something in your catch
that has a fathomable, known reason why it might throw another exception, you could put another try/catch
inside your catch
. It does happen - it's not unheard of - but it's uncommon.
If you have to call some other method in your catch
, it's good to know whether or not it is likely to throw an exception. It doesn't hurt to be familiar with your logging and make sure that it's not going to throw another exception. Or if it's some .NET Framework method, the documentation will usually tell you what exceptions it throws, and why.
Just as a random example, look at the documentation for the Remove
method of Dictionary<TKey, TValue>
:
Exceptions
Exception Condition
ArgumentNullException key is null
Then it tells you, in case you were wondering, what happens if you try to remove a key that doesn't exist.
If the Dictionary does not contain an element with the specified key, the Dictionary remains unchanged. No exception is thrown.
It can be very helpful to familiarize yourself with what's in the online documentation, including details like what exceptions a method throws.

- 5,347
- 4
- 31
- 41

- 27,588
- 3
- 45
- 62