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.
When an exception is raised, no further statements in the current block of code are executed.
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.
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.
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: ...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With