-2

I just wonder, when using try.. except, what's the difference between using the Base class "Except" and using a specific exception like "ImportError" or "IOError" or any other specific exception. Are there pros and cons between one and the other?

Andrés Orozco
  • 2,490
  • 5
  • 32
  • 48
  • specifically check out https://docs.python.org/3/tutorial/errors.html and see "if its type matches the exception named after the except keyword"; it's not about what you can do in the except clause, but about how control goes there or doesn't – nik.shornikov Sep 22 '16 at 18:46

2 Answers2

5

Never catch the base exception. Always capture only the specific exceptions that you know how to handle. Everything else should be left alone; otherwise you are potentially hiding important errors.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
0

Of course it has advantages using the correct exception for the corresponding issue. However Python already defined all possible errors for coding problems. But you can make your own exception classes by inheriting from the Exception class. This way you can make more meaningful errors for spesific parts of your code. You can even make the expections print errors like this.

SomeError: 10 should have been 5.

Provides easier debugging of the code.

For more info.

Community
  • 1
  • 1
Rockybilly
  • 2,938
  • 1
  • 13
  • 38