In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "what are the knowledge points of Python3 errors and anomalies". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn what are the knowledge points of Python3 errors and anomalies.
Grammatical error
Python syntax errors, or parsing errors, are often encountered by beginners, as shown in the following example
> while True print ('Hello world') File ", line 1, in? While True print ('Hello world') ^ SyntaxError: invalid syntax
In this example, the function print () is checked for an error because it is preceded by a colon:.
The parser indicates the line that went wrong and marks a small arrow where the error was first found.
Abnormal
Even if the syntax of the Python program is correct, errors can occur when running it. Errors detected at run time are called exceptions.
Most exceptions are not handled by the program and are shown here in the form of error messages:
> 10 * (1Traceback 0) # 0 cannot be used as a divisor. Trigger exception Traceback (most recent call last): File ", line 1, in? ZeroDivisionError: division by zero > 4 + spam*3 # spam is not defined, trigger exception Traceback (most recent call last): File", line 1, in? NameError: name 'spam' is not defined >' 2' + 2 # int cannot be added to str Trigger exception Traceback (most recent call last): File "", line 1, in? TypeError: Can't convert 'int' object to str implicitly
Exceptions occur in different types, all of which are printed as part of the information: the types in the example are ZeroDivisionError,NameError and TypeError.
The preceding 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.
Exception handling
Try/except
Exception catching can use the try/except statement.
In the following example, the user is asked to enter a valid integer, but the user is allowed to interrupt the program (using a method provided by Control-C or the operating system). The information interrupted by the user throws a KeyboardInterrupt exception.
While True: try: X = int (input ("Please enter a number:") break except ValueError: print ("you are not entering a number, please try to enter it again!")
The 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 is ignored. If the type of the exception matches the name after except, the corresponding except clause will be executed.
If an exception does not match any excep, the exception will be passed to the upper try.
A try statement may contain multiple except clauses to handle different specific exceptions. At most one branch will be executed.
The handler will handle only the exceptions in the corresponding try clause, not those in other try handlers.
An except clause can handle multiple exceptions at the same time, and these exceptions are placed in parentheses to form a tuple, for example:
Except (RuntimeError, TypeError, NameError): pass
The last except clause ignores the name of the exception and will be used as a wildcard. You can use this method to print an error message and then throw the exception again.
Import sys try: F = open ('myfile.txt') s = f.readline () I = int (s.strip ()) except OSError as err: print ("OS error: {0}" .format (err)) except ValueError: print ("Could not convert data to an integer.") except: print ("Unexpected error:", sys.exc_info () [0]) raise
Try/except...else
The try/except statement also has an optional else clause, which, if used, must be placed after all except clauses.
The else clause will be executed when there is no exception to the try clause.
The following example determines whether the file can be opened in the try statement, and executes the statement in the else section to read the contents of the file if there is no exception when opening the file:
For arg in sys.argv [1:]: try: F = open (arg,'r') except IOError: print ('cannot open', arg) else: print (arg,' has', len (f.readlines ()), 'lines') f.close ()
Using the else clause is better than putting all the statements in the try clause, which avoids unexpected exceptions that except cannot catch.
Exception handling handles not only those exceptions that occur directly in the try clause, but also those thrown in functions called (or even indirectly called) in the clause. For example:
> def this_fails (): X = 1 Handling run-time error:', err 0 > try: this_fails () except ZeroDivisionError as err: print ('Handling run-time error:', err) Handling run-time error: int division or modulo by zero
Try-finally statement
The try-finally statement executes the final code regardless of whether an exception occurs.
In the following example, the finally statement is executed regardless of whether an exception occurs:
Example
Try: runoob () except AssertionError as error: print (error) else: try: with open ('file.log') as file: read_data = file.read () except FileNotFoundError as fnf_error: print (fnf_error) finally: print (' this sentence is executed regardless of whether the exception occurs or not.')
Throw an exception
Python uses the raise statement to throw a specified exception.
The format of the raise syntax is as follows:
Raise [Exception [, args [, traceback]
The following example triggers an exception if x is greater than 5:
X = 10if x > 5: raise Exception ('x cannot be greater than 5. The value of x is: {} '.format (x))
Executing the above code triggers an exception:
X = 10if x > 5: raise Exception ('x cannot be greater than 5. The value of x is: {} '.format (x))
The only parameter to raise specifies the exception to be thrown. It must be an instance of an exception or an exception class (that is, a subclass of Exception).
If you just want to know if an exception is thrown and don't want to handle it, a simple raise statement can throw it again.
> try: raise NameError ('HiThere') except NameError: print (' An exception flew bylaws') Raise An exception flew bygone Traceback (most recent call last): File "", line 2, in? NameError: HiThere
User-defined exception
You can have your own exceptions by creating a new exception class. Exception classes inherit from the Exception class and can be inherited directly or indirectly, for example:
> > class MyError (Exception): def _ init__ (self, value): self.value = value def _ str__ (self): return repr (self.value) > try: raise MyError (2: 2) except MyError as e: print ('My exception occurred, value:', e.value) My exception occurred, value: 4 > > raise MyError ('oopsfolk') Traceback (most recent call last): File ", line 1 In? _ _ main__.MyError: 'oopsgiving'
In this example, the default _ _ init__ () of the class Exception is overridden.
When creating a module, it is possible to throw a variety of different exceptions, a common practice is to create a base exception class for the package, and then create different subclasses for different error situations based on this base class:
Class Error (Exception): "Base class for exceptions in this module." Pass class InputError (Error): "" Exception raised for errors in the input. Attributes: expression-- input expression in which the error occurred message-- explanation of the error "" def _ init__ (self, expression, message): self.expression = expression self.message = message class TransitionError (Error): "" Raised when an operation attempts a state transition that's not allowed. Attributes: previous-- state at beginning of transition next-- attempted new state message-- explanation of why the specific transition is not allowed "" def _ _ init__ (self, previous, next, message): self.previous = previous self.next = next self.message = message
Most exception names end with "Error", just like standard exception names.
Define cleanup behavior
The try statement has another optional clause that defines the cleanup behavior that will be performed in any case. For example:
> try:... Raise KeyboardInterrupt... Finally:... Print ('Goodbye, worldview'). Goodbye, Worldwide Traceback (most recent call last): File ", line 2, in KeyboardInterrupt
In the above example, the try clause is executed regardless of whether there is an exception in the finally clause or not.
If an exception is thrown in the try clause (or in the except and else clauses) and no except intercepts it, the exception is thrown after the finally clause is executed.
Here is a more complex example (including except and finally clauses in the same try statement):
> def divide (x, y): try: result = x / y except ZeroDivisionError: print ("division by zero!") Else: print ("result is", result) finally: print ("executing finally clause") > divide (2,1) result is 2.0executing finally clause > divide (2,0) division by zeroing execution finally clause > divide ("2", "1") executing finally clauseTraceback (most recent call last): File ", line 1, in? File "", line 3, in divideTypeError: unsupported operand type (s) for /: 'str' and' str'
Predefined cleanup behavior
Some objects define standard cleanup behavior, regardless of whether the system uses it successfully or not, once it is no longer needed, then the standard cleanup behavior will be performed.
This example shows an attempt to open a file and print the contents to the screen:
For line in open ("myfile.txt"): print (line, end= "")
The problem with the above code is that when the execution is complete, the file remains open and is not closed.
The keyword with statement ensures that objects such as files will execute their cleanup methods correctly after they are used:
With open ("myfile.txt") as f: for line in f: print (line, end= "")
After the execution of the above code, even if something goes wrong in the process, the file f will always be closed.
Thank you for your reading, the above is the content of "what are the knowledge points of Python3 errors and anomalies". After the study of this article, I believe you have a deeper understanding of what are the knowledge points of Python3 errors and anomalies, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.