PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 4, 2022

[FIXED] How to avoid duplicates when python multiple except executes the same method?

 August 04, 2022     exception, finally, python, try-except     No comments   

Issue

I have the code block like below:

try:
   method()
except ErrorType1:
   todo()
   return
except ErrorType2 as e:
   todo()
   raise e

Basically for the two error types, I need to execute todo() first, then either return or raise e. Is it possible to just write todo() once? I was thinking using finally but don't think that actually works.


Solution

You could catch both exceptions in one except clause, execute todo and then decide to do based on the exception type:

try:
   method()
except (ErrorType1, ErrorType2) as e:
   todo()
   if isinstance(e, ErrorType1):
       return
   raise

Note - as pointed out by @ShadowRanger in the comments to the question - you should just use raise to re-raise the existing exception, using raise e will raise a second copy of it, resulting in the traceback including the line with raise e on it as well as the line where the original error occurred.



Answered By - Nick
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing