YTread Logo
YTread Logo

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

Apr 27, 2024
Benjamin Franklin once said if you don't plan, you are planning to fail in your defense. said this before the computer age today we review this quote if you don't plan for failure you are planning to fail as an engineer this is because if there is a way for the code to break then somehow someone will break it , believe me, using

exceptions

. You can handle these issues responsibly. If a client asks you to capitalize an integer, you can reject his strange suggestion and if someone asks you to divide it by. zero, then you can throw an exception letting them know what they can do with their split request.
exceptions in python python tutorial learn python programming
Once you

learn

how to do this, you will become an exceptional Python engineer. When Python encounters an error while executing your code, it will stop execution and throw 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's start by looking at some of the most common exceptions and then we'll move on. Learn how to handle exceptions when they occur and raise exceptions when necessary to illustrate exceptions. I'm going to deliberately make mistakes in my code.
exceptions in python python tutorial learn python programming

More Interesting Facts About,

exceptions in python python tutorial learn python programming...

The mere thought of this makes my neural networks rebel, but this is for a good cause, we will eliminate these errors. in a file called dot py exceptions underscore

tutorial

, let's first write some code to print hello world five times and then run instead of our welcome message, there was a problem, the last line shows the type of error found, an error of syntax, it also provides a concise description. Problem Invalid Syntax A syntax error means that you didn't follow the rules for how to write Python code. You will encounter this frequently when you are first

learn

ing Python.
exceptions in python python tutorial learn python programming
You will see a text telling you where the problem occurred. This text is called. in fact, a Python traceback displays a caret pointing to the precise location of the syntax error. Here we see that we are missing two points at the end of the for loop. If we add the colon and then run again, everything works as expected, let's look at some. most common exceptions before we learn how to throw and handle them, one divide by zero, run Python knows this is not possible, so it generates a zero division error with a redundant description, traceback lets you know the file and the line where this mathematical sin was committed if you add some blank lines at the beginning and run again then the line number in the traceback also changes.
exceptions in python python tutorial learn python programming
Next, let's open the x files and read the contents. It will be exciting to read it. Why am I not surprised when a file cannot be found? Python generates a file not found error, the truth must still be out there, what happens if you try to add one, two and three, but instead of the integer three you use the word three, how did I laugh while writing? Here you get a type error with more useful text. description Python lets you know that you can't add an integer and a string. This exception is very common. Occurs when you expect one type of data but receive another for the next illustration.
Import the math module and then take the square root of the negative. I'm not. I am amused by the answer: we know that for centuries the mathematical function expects a number that we provide so that there is no type error, but apparently it is afraid of negative numbers, so it generates 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 show them in a hierarchy to show the parent class of each exception class. Python does this to organize logically. 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 element in a list or tuple that is out of range the key error occurs when If 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.
A final note note how most of these class names end in error and not exception why. This is because that's how it's done in Python. The general way to handle exceptions is try, except that eventually the construct can have more than one exception clause if necessary. This gives you the ability to respond to different exceptions in different ways. Python starts by trying to execute the code in the try block if a problem occurs, jumps to the first matching accept block and executes that code if no problem occurs, after the try block finishes, Python will skip all accept blocks and will execute the else code and finally the final block, this code will be executed regardless of what happens above, error or no error, the finally block will always be executed, let's see an example, we will write a function that will read the contents of a binary file and return the data, but as an extra touch.
We will measure the time needed to do this. This is something you could do if you are running a cloud service that creates users based on time used. We'll be logging our results and timing code, so first import the logging and time modules and create a base. logger with debug level we will use this logger to log the exceptions and the time used now we will define the function the input is the path to the binary file next we will demonstrate its responsible nature by writing a docstring first we will record the time when the method started next we will try to open the binary file and return the contents by default, open assumes that you are opening a file in text reading mode, we will override this default and open the file in binary reading mode, then we will read the contents of the file and then we will return the data if the file does not.
Python does not exist will generate a file not found error. We can handle this situation with an accept line, type the keyword, accept the exception class name, and then give the exception a name. This assigns the exception object to a variable called err. You can name your exception, anything you want, in case the file does not exist we will log the error, there is not much else we can do and there is no point in returning anything, so we can write the upload command to tell Python to pass file no. error found for the user then we write an else block this code is only executed 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 an object from file and finally the final block this code always executes if everything worked or if there was an exception it doesn't matter here we record the stop time we calculate the time required and then record the value in reality you would probably store the required time in a database , but for simplicity, we are recording the time this function uses the four parts of the job with exceptions.
Try to accept the rest and finally it's time to test it, we will read an audio file and execute it, no errors were generated and if you notice in 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 that it took a little longer to read the video file. Then try reading a file that doesn't exist uh-oh, this file doesn't exist and the function passed the file not found error to us to handle. If you look at the log file once more you will see the error message along with zero time required, our users will be sad. about the lack of data, but happy that there will be no charge, a wise creature once said: do it or not, there is no try, apparently yoda never wrote code because when you write software you try everywhere.
Now I will try to convince you to support. We at Patreon, if you raise a Money Not Found bug, we will completely understand; Otherwise, any support you can offer will make me smile inside.

If you have any copyright issue, please Contact