Exceptions in Python || Python Tutorial || Learn Python Programming

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
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 trace back 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 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're first learning Python above you will see some text that tells you where the problem occurred this text is called a trace back in fact Python displays a carrot 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 1/0 run Python knows this is not possible so it raises a 0 division error with a redundant description the trace back 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 trace back 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 map 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 and an error and not exceptions 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 except block and execute that code if no problem occurs then after the try block is finished Python will skip all the except blocks and run the else code and finally the finally 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 are running a cloud service that build users buy time used we will be logging our results and timing the code so import the logging in 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 doc string 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 and 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 eerr 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 finally 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 except else and finally it is now time to test it first 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 on to 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]
Info
Channel: Socratica
Views: 217,787
Rating: 4.9415436 out of 5
Keywords: Socratica, SocraticaCS, python, python programming, python tutorial, computer science, exception, exceptions, try, except, else, finally, exception handling, python exceptions
Id: nlCKrKGHSSk
Channel Id: undefined
Length: 9min 1sec (541 seconds)
Published: Sat Jun 02 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.