benjamin franklin once said if you fail to plan you're planning to fail in his defense he said this before the computing era today we revise this quote if you fail to plan for failure you are planning to fail as an engineer this is because if there is a way for code to break then somehow somewhere someone will break it trust me using exceptions you can manage these problems in a responsible way if a client asks you to capitalize an integer you can decline their bizarre suggestion and if someone asks you to divide by zero then
you can throw an exception letting them know what they can do with their division request once you learn how to do this you will become an exceptional python engineer when python encounters an error while running your code it stops execution and raises an exception an exception is an object with a description of what went wrong and a traceback of where the problem occurred there are many different types of exceptions built into python each one describes different types of problems let us begin by looking at some of the most common exceptions then we will learn how
to handle exceptions when they occur and raise exceptions when necessary to illustrate the exceptions i am going to deliberately make mistakes in my code the mere thought of this causes my neural nets to rebel but this is for a good cause we will put these mistakes in a file called exceptions underscore tutorial dot py let us first write some code to print hello world five times then run instead of our welcoming message there was a problem the last line displays the type of error encountered a syntax error it also gives a terse description of the
problem invalid syntax a syntax error means you did not follow the rules for how to write python code you will encounter this a lot when you are first learning python above you will see some text that tells you where the problem occurred this text is called a traceback in fact python displays a caret pointing to the precise location of the syntax error here we see that we are missing a colon at the end of the for loop if we add the colon then run again everything works as intended let us see a few more common
exceptions before we learn how to throw and handle them one divided by zero run python knows this is not possible so it raises a zero division error with a redundant description the traceback lets you know the file and line where this mathematical sin was committed if you add a few blank lines at the beginning and run again then the line number in the traceback also changes next let us open the x files and read the contents this will be exciting to read why am i not surprised whenever a file cannot be found python raises a
file not found error the truth must still be out there what if you try to add one two and three but instead of the integer three you use the word three how i laughed while typing that here you get a type error with a more helpful description python lets you know that you cannot add an integer and a string this exception is very common it occurs when you expect one type of data but receive another for the next illustration import the math module then take the square root of negative one i am not amused the
answer is i we've known that for centuries the math function expects a number which we provide so there is no type error but apparently it is afraid of negative numbers so it raises a value error this is used when the type is correct but the value is something that cannot be handled python comes with a large collection of built-in exceptions here we display them in a hierarchy to show the parent class of each exception class python does this to logically organize the many exceptions for example look at the sub-branch there are two built-in exceptions that
are subclasses of lookup error the index error occurs when you try to access an item in a list or tuple that is out of range the key error happens when you try to look up a value in a dictionary using an invalid key in your own code use one of the built-in exceptions whenever possible but if necessary you can create your own exception by subclassing the exception class one final note notice how most of these class names end in error and not exception why is this because that is how it is done in python the
general way for handling exceptions is the try except else finally construction you can have more than one exception clause if necessary this gives you the ability to respond to different exceptions in different ways python begins by trying to execute the code in the try block if a problem occurs it jumps to the first matching accept block and executes that code if no problem occurs then after the try block is finished python will skip all the accept blocks and run the else code and finally the final block this code will run regardless of what happens above
error or no error the finally block will always execute let us see an example we will write a function that will read the contents of a binary file and return the data but as an added twist we will measure the time required to do this this is something you might do if you're running a cloud service that build users by time used we will be logging our results and timing the code so import the logging and time modules first create a basic logger with debug level we will use this logger to record both exceptions and
time used now define the function the input is the path to the binary file next demonstrate your responsible nature by writing a docstring first we record the time the method began next we will try to open the binary file and return the contents by default open assumes you are opening a file in read text mode we will override this default and open the file in read binary mode next read the contents of the file then return the data if the file does not exist python will raise a file not found error we can handle this
situation with an accept line type the keyword accept the name of the exception class and then give the exception a name this assigns the exception object to a variable named err you can name your exception anything you like in the event the file does not exist we will log the error there is not much more we can do and it does not make sense to return anything so we can type the raise command to instruct python to pass along the file not found error to the user next we write an else block this code only
executes if there are no exceptions in the try block in this case we want to close the file we cannot close the file in the finally block because if the file does not exist f will not be a file object and finally the final block this code always executes if everything worked or if there was an exception it does not matter here we record the stop time compute the time required then log the value in reality you would likely store the time required in a database but for simplicity we are logging the time this function
uses all four parts of working with exceptions try accept else and finally it is now time to test it we will read an audio file run no errors were raised and if you look at the log file you can see the time required to read and return this audio file next let's read a much larger video file again everything worked fine and the log file showed it took a bit longer to read the video file next try to read a file that does not exist uh-oh this file does not exist and the function passed the
file not found error onto us for handling if you look at the log file once more you will see the error message along with the time required zero our users will be sad about the lack of data but happy there will be no charge a wise creature once said do or do not there is no try apparently yoda never wrote code because when writing software you are trying all over the place i will now try to convince you to support us on patreon if you raise a money not found error we will completely understand else
any support you can offer will make me smile on the inside [Music] you