In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces "the exception handling of Python". In the daily operation, I believe that many people have doubts about the exception handling of Python. The editor consulted all kinds of data and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "exception handling of Python". Next, please follow the editor to study!
Python provides two very important functions to handle exceptions and errors that occur when python programs are running. You can use this feature to debug python programs.
Exception handling
Assertion (Assertions)
Python standard anomaly
Exception name
Description
BaseException
The base class of all exceptions
SystemExit
Interpreter request exit
KeyboardInterrupt
The user interrupts execution (usually by entering ^ C)
Exception
Base class of general error
StopIteration
Iterator has no more values
GeneratorExit
An exception occurred in the generator (generator) to notify the exit
SystemExit
Python interpreter request exit
StandardError
The base class of all built-in standard exceptions
ArithmeticError
The base class of all numerical calculation errors
FloatingPointError
Floating point calculation error
OverflowError
The numerical operation exceeds the maximum limit
ZeroDivisionError
Divide (or modulo) zero (all data types)
AssertionError
Assertion statement failed
AttributeError
Object does not have this property
EOFError
No built-in input, arriving at the EOF tag
EnvironmentError
Base class of operating system error
IOError
Input / output operation failed
OSError
Operating system error
WindowsError
System call failed
ImportError
Failed to import module / object
KeyboardInterrupt
The user interrupts execution (usually by entering ^ C)
LookupError
Base class for invalid data query
IndexError
There is no such index in the sequence (index)
KeyError
This key is not in the mapping
MemoryError
Memory overflow error (not fatal for Python interpreter)
NameError
Object not declared / initialized (no properties)
UnboundLocalError
Access uninitialized local variables
ReferenceError
Weak references (Weak reference) attempt to access objects that have been garbage collected
RuntimeError
General runtime errors
NotImplementedError
Methods that have not yet been implemented
SyntaxError
Python syntax error
IndentationError
Indent error
TabError
Tab mixed with spaces
SystemError
General interpreter system error
TypeError
Operation that is not valid for type
ValueError
Pass in invalid parameters
UnicodeError
Unicode related errors
UnicodeDecodeError
Errors in Unicode decoding
UnicodeEncodeError
Error in Unicode coding
UnicodeTranslateError
Error in Unicode conversion
Warning
Base class of warning
DeprecationWarning
Warning about deprecated features
FutureWarning
Warning about semantic changes in construction in the future
OverflowWarning
Old warning about automatic promotion to long integer (long)
PendingDeprecationWarning
Warning that the feature will be discarded
RuntimeWarning
Warning of suspicious runtime behavior (runtime behavior)
SyntaxWarning
A warning of suspicious syntax
UserWarning
Warnings generated by user code
What is an anomaly?
An exception is an event that occurs during the execution of the program, affecting the normal execution of the program.
In general, an exception occurs when Python fails to handle the program properly.
The exception is a Python object that represents an error.
When an exception occurs in the Python script, we need to capture and handle it, otherwise the program will terminate execution.
Exception handling
You can use the try/except statement to catch exceptions.
The try/except statement is used to detect errors in the block of try statements, allowing the except statement to catch exception information and handle it.
If you don't want to end your program when an exception occurs, just capture it in try.
Syntax:
The following is the syntax for the simple try....except...else:
Try:
# run other code
Except:
# if a 'name' exception is thrown in the try section
Except,:
# if a 'name' exception is thrown, get additional data
Else:
# if no exception occurs
How try works is that when you start a try statement, python marks it in the context of the current program, so that you can come back here when an exception occurs, the try clause executes first, and what happens next depends on whether the exception occurs during execution.
If an exception occurs when a statement after try executes, python jumps back to try and executes the first except clause that matches the exception. After the exception is handled, the control flow passes through the entire try statement (unless a new exception is thrown when the exception is handled).
If an exception occurs in the statement after try, but there is no matching except clause, the exception will be submitted to the upper try, or to the top of the program (which will end the program and print the default error message).
If no exception occurs during the execution of the try clause, python executes the statement after the else statement (if there is an else), and then controls the flow through the entire try statement.
Example
Here is a simple example that opens a file where the contents are written without exception:
#! / usr/bin/python
Try:
Fh = open ("testfile", "w")
Fh.write ("This is my test file for exception handling!")
Except IOError:
Print "Error: can\'t find file or read data"
Else:
Print "Written content in the file successfully"
Fh.close ()
The above program outputs the results:
Written content in the file successfully
Example
The following is a simple example that opens a file in which the contents are written, but the file does not have write permission, and an exception occurs:
#! / usr/bin/python
Try:
Fh = open ("testfile", "w")
Fh.write ("This is my test file for exception handling!")
Except IOError:
Print "Error: can\'t find file or read data"
Else:
Print "Written content in the file successfully"
The above program outputs the results:
Error: can't find file or read data
Use except without any exception types
You can use except without any exception types, such as the following example:
Try:
You do your operations here
..
Except:
If there is any exception, then execute this block.
..
Else:
If there is no exception then execute this block.
In the above way, the try-except statement catches all exceptions that occur. But this is not a good way, we can not identify specific abnormal information through this program. Because it catches all exceptions.
Use except with multiple exception types
You can also use the same except statement to handle multiple exception messages, as shown below:
Try:
You do your operations here
..
Except (Exception1 [, Exception2 [,... ExceptionN]):
If there is any exception from the given exception list
Then execute this block.
..
Else:
If there is no exception then execute this block.
Try-finally statement
The try-finally statement executes the final code regardless of whether an exception occurs.
Try:
Finally:
# always execute when you exit try
Raise
Note: you can use either the select statement or the finally statement, but not both. Else statements cannot be used with finally statements at the same time
Example
#! / usr/bin/python
Try:
Fh = open ("testfile", "w")
Fh.write ("This is my test file for exception handling!")
Finally:
Print "Error: can\'t find file or read data"
If you open a file that does not have writeable permissions, the output is as follows:
Error: can't find file or read data
The same example can also be written as follows:
#! / usr/bin/python
Try:
Fh = open ("testfile", "w")
Try:
Fh.write ("This is my test file for exception handling!")
Finally:
Print "Going to close the file"
Fh.close ()
Except IOError:
Print "Error: can\'t find file or read data"
When an exception is thrown in a try block, the finally block code is executed immediately.
After all statements in the finally block are executed, the exception is raised again and the except block code is executed.
The content of the parameter is different from the exception.
Abnormal parameters
An exception can take a parameter and can be used as an exception information parameter of the output.
You can catch abnormal parameters through the except statement, as shown below:
Try:
You do your operations here
..
Except ExceptionType, Argument:
You can print value of Argument here...
The outliers received by variables are usually contained in the exception statement. Variables can receive one or more values in the form of a tuple.
Tuples usually contain error strings, error numbers, and error locations.
Example
The following is an example of a single exception:
#! / usr/bin/python
# Define a function here.
Def temp_convert (var):
Try:
Return int (var)
Except ValueError, Argument:
Print "The argument does not contain numbers\ n", Argument
# Call above function here.
Temp_convert ("xyz")
The results of the above procedures are as follows:
The argument does not contain numbers
Invalid literal for int () with base 10: 'xyz'
Trigger exception
We can use the raise statement to trigger the exception ourselves
The format of the raise syntax is as follows:
Raise [Exception [, args [, traceback]
The Exception is the type of exception in the statement (for example, NameError) the parameter is an exception parameter value. This parameter is optional, and if not provided, the exception parameter is "None".
The last parameter is optional (rarely used in practice) and, if present, tracks the exception object.
Example
An exception can be a string, class, or object. Most of the exceptions provided by Python's kernel are instantiated classes, which are parameters for an instance of a class.
Defining an exception is very simple, as follows:
Def functionName (level):
If level < 1:
Raise "Invalid level!", level
# The code below to this would not be executed
# if we raise the exception
Note: in order to catch an exception, the "except" statement must use the same exception to throw a class object or string.
For example, if we catch the above exception, the "except" statement is as follows:
Try:
Business Logic here...
Except "Invalid level!":
Exception handling here...
Else:
Rest of the code here...
User-defined exception
By creating a new exception class, programs can name their own exceptions. Exceptions should typically inherit from the Exception class, either directly or indirectly.
The following is an example related to RuntimeError, in which a class is created with the base class RuntimeError, which is used to output more information when an exception is triggered.
In the try statement block, the except block statement is executed after a user-defined exception, and the variable e is used to create an instance of the Networkerror class.
Class Networkerror (RuntimeError):
Def _ _ init__ (self, arg):
Self.args = arg
After you define the above class, you can trigger the exception, as shown below:
Try:
Raise Networkerror ("Bad hostname")
Except Networkerror,e:
Print e.args
At this point, the study of "exception handling of Python" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.