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