Home > Blockchain >  Too broad exception clause
Too broad exception clause

Time:08-01

I have just one question.

In pycharm we get warning for except block like below

try:
    <code>
except Exception: #=> Too broad exception clause
    <code>

Just want to know apart from best practice and all, what is harm in doing so. Does it increase complexity? If there is any negative point of this please provide some official docs too.

Edit: I know my example was misleading. If I was talking about bare except block then I would have mentioned that. I have updated my example, which gives same warning.

CodePudding user response:

Do not use bare except clause. https://www.flake8rules.com/rules/E722.html will help.

You should check out PEP8 too. (https://peps.python.org/pep-0008/)

CodePudding user response:

Whats the purpose of using try except

  • Handle error

  • There are several types of error and surely all type of error can't be handled in a same way

  • So if you want to handle an error you need to know what's the error

    • TypeError, ValueError, NameError etc.
  • Suppose in my code I will expecting int value and if I will got float my code will throw error (To handle specific type error my approach)

  •   a = '2'
      try:
          b = a/2
      except TypeError:
          a = int(a)
          b = a/2
      b = b*4
    
  • If I will got sometype of string which can't be converted into int then my code will throw an error and the later part will not be executed b = b*4

So mentioning a specific error will handle specific error in the try except block, which gives us a better control on our code.

If you mentioned try except, It will pass the try except block no matter what type of error appeared and try to execute later part of your code

  • Which causes error at unexpected place
  • Related