Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible an Exception object raising another exception due to its internal error?

Tags:

c#

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.

like image 393
xport Avatar asked Jul 29 '10 08:07

xport


People also ask

What happens when an exception is raised?

When an exception is raised, no further statements in the current block of code are executed.

Is throwing exception good practice?

The short answer is NO. You would throw an exception if the application can't continue executing with the bad data. In your example, the logic is to display an error message on the front end and Option 2 is the cleaner method for achieving this requirement.

How do you raise an exception class in Python?

As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.

What is except exception as e?

except: accepts all exceptions, whereas. except Exception as e: only accepts exceptions that you're meant to catch. Here's an example of one that you're not meant to catch: >>> try: ...


1 Answers

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 try block, the catch will catch it (assuming it catches the appropriate type of exception). If you are instantiating it in the catch block, you may want to do that in a nested try{}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 OutOfMemory or unexpected StackOverflow), as you don't have a way to deal with them.

like image 105
Oded Avatar answered Oct 18 '22 18:10

Oded