Python3 error and exceptions
As a Python beginner, when you first learn Python programming, you will often see some error messages. We didn't mention them in the previous section. We will introduce them in this chapter.
Python has two types of errors that are easy to identify: syntax errors and exceptions.
Python's syntax errors, or parsing errors, are common to beginners, as in the following examples
In this example, the function print() is checked for errors, which is missing a colon (:) in front of it.
The parser pointed out the line that was in error and marked a small arrow at the location of the error found first.
Even if the syntax of the Python program is correct, an error may occur while running it. Errors detected during runtime are called exceptions.
Most exceptions are not handled by the program and are presented here as error messages:
Exceptions appear in different types, and these types are printed as part of the information: The types in the examples are ZeroDivisionError, NameError, and TypeError.
The front part of the error message shows the context in which the exception occurred and displays the specific information in the form of a call stack.
In the following example, let the user enter a valid integer, but allow the user to interrupt the program (using Control-C or the method provided by the operating system). User interrupted messages will raise a KeyboardInterrupt exception.
try statement works as follows;
- First, execute the try clause (the statement between the keyword try and the keyword except)
- If no exception occurs, the except clause is ignored and the try clause ends after execution.
- If an exception occurs during the execution of the try clause, the rest of the try clause will be ignored. If the type of the exception matches the name after except, the corresponding except clause will be executed. Finally execute the code after the try statement.
- If an exception does not match any except, then the exception will be passed to the upper try.
A try statement may contain multiple except clauses to handle different specific exceptions. At most only one branch will be executed.The
handler will only handle exceptions in the corresponding try clause, not exceptions in other try handlers.
An exception clause can handle multiple exceptions at the same time. These exceptions will be placed in parentheses as a tuple, for example:
The last except clause can ignore the name of the exception and it will be used as a wildcard. You can use this method to print an error message and then throw the exception again.
try except statement also has an optional else clause. If you use this clause, you must put it after all the except clauses. This clause will be executed when there is no exception in the try clause. E.g:
It's smarter to utilize the else provision than to put every one of the announcements in the attempt statement, so you can dodge unforeseen special cases that are not gotten by with the exception of.
Exception taking care of does not just arrangement with special cases that happen straightforwardly in the attempt proviso, yet additionally handles exemptions tossed in capacities brought in provisos (or even in a roundabout way called capacities). For example:
Throw an exception
Python uses the raise statement to throw a specified exception. For example:
raise The only parameter that specifies the exception to be thrown. It must be an exception instance or an exception class (that is, a subclass of Exception ).
If you just want to know if this throws an exception and doesn't want to handle it, then a simple raise statement can throw it again.
You can have your own exception by creating a new exception class. Exception classes inherit from the Exception class and can be inherited directly or indirectly, for example:
The names of most exceptions end with "Error", just like the standard exception name.
Define cleanup behaviorThe
try statement has an optional clause that defines the cleanup behavior that will be performed under any circumstances. For example:
The above model will execute paying little heed to whether there is a special case in the attempt condition.
If an exemption is tossed in the attempt statement (or in the aside from and else conditions) with no special case capturing it, at that point the exemption will be tossed again after the at long last proviso is executed. .
The following is an increasingly confounded precedent (with the aside from lastly provisos in a similar attempt statement):
Predefined cleanup behavior
Some objects characterize standard cleanup conduct, paying little respect to whether the framework effectively utilized it, and once it isn't required, at that point this standard cleanup conduct will be performed.
This model shows endeavoring to open a document and afterward print the substance to the screen:
The issue with this code is that when the execution is finished, the document will stay open and not shut.
The catchphrase with proclamation guarantees that items, for example, documents will accurately execute their cleanup strategies after they are used:
After the above code is executed, regardless of whether there is an issue amid preparing, the document f will dependably be shut.