Is it possible an Exception object raising another exception due to its internal error?
Assume in try-catch we instantiate Exception object, is it possible the instantiation raising another exception? If yes, we must nest infinitely try-catch blocks that looks so funny.
In short, the answer is yes, it is possible.
For example – if the exception class requires a large object to be initialized as a field, but there is not enough memory to allocate it, you will get an exception object that would throw an
OutOfMemoryException.Exceptions are like any other class and can in themselves throw exceptions. There is nothing in the language that disallows it.
I would say, however, that throwing exceptions from an exception class it bad practice and should generally be avoided.
Update: (following updated question)
If you are instantiating an exception object in a
tryblock, thecatchwill catch it (assuming it catches the appropriate type of exception). If you are instantiating it in thecatchblock, you may want to do that in a nestedtry{}catch{}– this is quite normal for code used in a catch block that can throw exceptions.As others have said – some exceptions should not be caught (for instance
OutOfMemoryor unexpectedStackOverflow), as you don’t have a way to deal with them.