#100DaysOfCode in Python Transcripts
Chapter: Days 34-36: Refactoring / Pythonic code
Lecture: Refactoring 9: be explicit in your exceptions
Login or purchase this course to watch this video and the rest of the course contents.
0:00 One thing that the Zen is saying is explicit is better than implicit and I want to show you that concept with a couple of examples here.
0:09 For example, if you do a from module import *, it imports everything in your namespace if this would
0:15 import full or bar and you define such a variable or function that will override it and that leads to very obscure box. So don't do import *.
0:25 Make it explicit what you're importing. So from module import full, bar. Another coding horror is something like try and except pass.
0:37 Now this is like the black hole or monster that absorbs all possible errors, muting them away and you won't see anything in return.
0:46 So whatever happens, even if I were to interrupt the program with a control C which would raise the keyboard interrupt exception,
0:54 that will be silenced as well so I cannot even kill my program basically. So don't do this. No bare exceptions, make it explicit.
1:03 So a little bit better will be for example, at least I get some information, or let's divide it by 0, I'm still shouting
1:20 and I get another error. And you see these operations lead to different exceptions so the best way to do it is to explicitly name the exceptions.
1:33 Again, try to divide number one by number two and let's go through the different exceptions we might get.
1:45 Here for example, if I get a ZeroDivision error, I just return 0. That's my handling of the exception. If I get a type error,
1:55 and here I just print a message but I don't really have a way to allow this and so I just reraise the exception.
2:02 And if something else goes wrong you still can instead of doing accept pass or accept print something you can at least
2:09 say accept exception as variable and browse that variable. And you can send this to a log file for example.
2:15 To have at least a little bit more information when you're debugging the problem. So now it's from the cell and call it with a string.
2:32 And here you see that it entered the type error and I get the message related to type error and it reraised the exception and if I divide by 0,
2:43 here we don't have to crash anymore because I explicitly handled ZeroDivision error. Printed the message and return 0.
2:50 Great, and that concludes number 9. Explicit is better than implicit.