raise

How to re-raise an exception in nested try/except blocks?

时光毁灭记忆、已成空白 提交于 2019-11-26 19:16:29
问题 I know that if I want to re-raise an exception, I simple use raise without arguments in the respective except block. But given a nested expression like try: something() except SomeError as e: try: plan_B() except AlsoFailsError: raise e # I'd like to raise the SomeError as if plan_B() # didn't raise the AlsoFailsError how can I re-raise the SomeError without breaking the stack trace? raise alone would in this case re-raise the more recent AlsoFailsError . Or how could I refactor my code to

How to use “raise” keyword in Python [duplicate]

痞子三分冷 提交于 2019-11-26 12:34:34
问题 This question already has an answer here: Manually raising (throwing) an exception in Python 7 answers I have read the official definition of \"raise\", but I still don\'t quite understand what it does. In simplest terms, what is \"raise\"? Example usage would help. 回答1: It has 2 purposes. yentup has given the first one. It's used for raising your own errors. if something: raise Exception('My error!') The second is to reraise the current exception in an exception handler, so that it can be

Don't show Python raise-line in the exception stack

安稳与你 提交于 2019-11-26 11:06:21
问题 When I raise my owns exceptions in my Python libraries, the exception stack shows the raise-line itself as the last item of the stack. This is obviously not an error, is conceptually right, but points the focus on something that is not useful for debugging when you\'re are using code externally, for example as a module. Is there a way to avoid this and force Python to show the previous-to-last stack item as the last one, like the standard Python libraries. 回答1: Due warning: modifying the

Best practice for Python assert

▼魔方 西西 提交于 2019-11-26 03:18:59
问题 Is there a performance or code maintenance issue with using assert as part of the standard code instead of using it just for debugging purposes? Is assert x >= 0, \'x is less than zero\' better or worse than if x < 0: raise Exception, \'x is less than zero\' Also, is there any way to set a business rule like if x < 0 raise error that is always checked without the try/except/finally so, if at anytime throughout the code x is less than 0 an error is raised, like if you set assert x < 0 at the