Python provides two very important features to handle the exceptions and errors that Python programs run in. You can use this feature to debug a python program.
Exception handling: This site Python tutorial will be described in detail.
Assertion (Assertions): This site Python tutorial will be described in detail.
Python Standard exception
Exception name
Describe
Baseexception base class for all exceptions
Systemexit Interpreter Request Exit
Keyboardinterrupt user interrupt execution (usually input ^c)
Exception base class for general errors
Stopiteration iterator with no more values
Generatorexit Generator (generator) exception occurred to notify exit
Systemexit Python interpreter request to exit
StandardError base class for all built-in standard exceptions
Arithmeticerror base class for all numeric calculation errors
Floatingpointerror floating-point calculation error
Overflowerror numeric operation exceeds maximum limit
Zerodivisionerror except (or modulo) 0 (all data types)
Assertionerror Assertion Statement failed
Attributeerror object does not have this property
Eoferror has no built-in input to reach the EOF tag
EnvironmentError base class for operating system errors
IOError Input/output operation failed
OSError Operating system error
Windowserror system call failed
Importerror Import Module/object failed
Keyboardinterrupt user interrupt execution (usually input ^c)
Lookuperror base class for invalid data queries
There is no this index (index) in the indexerror sequence
This key is not in the Keyerror map
Memoryerror Memory overflow error (not fatal for Python interpreter)
Nameerror object not declared/initialized (no attributes)
Unboundlocalerror access to uninitialized local variables
Referenceerror Weak reference (Weak reference) attempts to access objects that have been garbage collected
RuntimeError General run-time errors
Notimplementederror methods that have not yet been implemented
SyntaxError Python Syntax error
Indentationerror Indent Error
Taberror Tab and Space mix
Systemerror General Interpreter System error
TypeError operations that are not valid for types
ValueError invalid arguments passed in
Unicodeerror Unicode-related errors
Unicodedecodeerror Unicode decoding Error
Unicodeencodeerror Unicode Encoding Error
Unicodetranslateerror Unicode Conversion Error
Base class for Warning warnings
Deprecationwarning warning about deprecated features
Futurewarning warning about the change in the construction of future semantics
overflowwarning old warning about auto-promotion to Long integer
Pendingdeprecationwarning warnings about attributes that will be discarded
Runtimewarning warning for suspicious runtime behavior (runtime behavior)
Syntaxwarning warning of suspicious syntax
Userwarning warning for user code generation
What is an exception?
An exception is an event that occurs during program execution and affects the normal execution of the program.
In general, an exception occurs when Python does not handle the program properly.
The exception is a Python object that represents an error.
When a Python script exception occurs, we need to capture and process it, or the program terminates execution.
Exception handling
You can use the Try/except statement to catch an exception.
The try/except statement is used to detect errors in a try statement block, allowing the except statement to catch exception information and handle it.
If you do not want to end your program when an exception occurs, simply capture it in a try.
Grammar:
The following is a simple syntax for try....except...else:
Try
< statements > #运行别的代码
Except < name:
< statement > #如果在try部份引发了 ' name ' exception
Except < name >,< data;:
< statement > #如果引发了 ' name ' exception to get additional data
Else
< statements > #如果没有异常发生
Try works by starting a try statement, and Python is tagged in the context of the current program so that when an exception occurs, it can go back here, the TRY clause executes first, and what happens next depends on whether an exception occurs at execution time.
If an exception occurs when the statement after the try is executed, Python jumps back to the try and executes the first except clause that matches the exception, and 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 the try, but there is no matching except clause, the exception will be submitted to the upper try, or to the top of the program (This will end the program and print the default error message).
If no exception occurs when the TRY clause executes, Python executes the statement after the Else statement (if there is else), and then the control flow passes through the entire try statement.
Instance
Here is a simple example that opens a file where the contents of the file are written and the exception does not occur:
#!/usr/bin/python
Try
FH = open ("Testfile", "W")
Fh.write ("This was 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 output results:
Written content in the file successfully
Instance
Here is a simple example that opens a file where the contents of the file 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 was 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 output results:
Error:can ' t find file or read data
Use except without any exception type
You can use except without any exception type, as in the following example:
Try
your operations here;
......................
Except
If there is any exception and then execute this block.
......................
Else
If there is no exception then execute this block.
The try-except statement above captures all occurrences of the exception. But this is not a good way to identify specific exception information through the program. Because it catches all the exceptions.
Using except with multiple exception types
You can also use the same except statement to handle multiple exception information, as follows:
Try
your operations here;
......................
Except (exception1[, exception2[,... Exceptionn]]):
If there is a exception from the given exception list,
Then execute the this block.
......................
Else
If there is no exception then execute this block.
try-finally statements
The try-finally statement executes the final code regardless of whether an exception occurs.
Try
< statements >
Finally
< statements > #退出try时总会执行
Raise
Note: You can use the except statement or the finally statement, but both cannot be used at the same time. Else statement cannot be used in conjunction with the finally statement
Instance
#!/usr/bin/python
Try
FH = open ("Testfile", "W")
Fh.write ("This was my test file for exception handling!!")
Finally
print "error:can\ ' t find file or read data"
If the open file does not have writable permissions, the output is as follows:
Error:can ' t find file or read data
The same example can be written in the following way:
#!/usr/bin/python
Try
FH = open ("Testfile", "W")
Try
Fh.write ("This was 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"
Executes the finally block code immediately when an exception is thrown in the try block.
After all the statements in the finally block are executed, the exception is raised again, and the except block code is executed.
The contents of the parameter differ from the exception.
parameter of the exception
An exception can take a parameter that can be used as the output exception information parameter.
You can use the except statement to catch the parameters of the exception, as follows:
Try
your operations here;
......................
Except Exceptiontype, Argument:
You can print value of Argument here ...
The exception value that the variable receives is usually contained in the exception's statement. In a tuple's form, a variable can receive one or more values.
Tuples typically contain error strings, error numbers, and error locations.
Instance
The following is an instance 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 program execution are as follows:
The argument does not contain numbers
Invalid literal for int. () with base: ' XYZ '
Triggering an exception
We can use the raise statement to trigger the exception ourselves
The raise syntax format is as follows:
raise [Exception [, Args [, Traceback]]
The type of exception in the statement is an exception (for example, the Nameerror) 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, is the tracking exception object.
Instance
An exception can be a string, a class, or an object. The Python kernel provides exceptions, most of which are instantiated classes, which are parameters of an instance of a class.
It is very simple to define an exception as follows:
def functionname (level):
If level < 1:
Raise "Invalid level!", Level
# The code below to this would isn't be executed
# If we raise the exception
Note: To be able to catch exceptions, the "except" statement must have the same exception to throw the class object or string.
For example, we capture the above exception, and the "except" statement looks like this:
Try
Business Logic-here ...
Except "Invalid level!":
Exception Handling here ...
Else
Rest of the code here ...
User-defined exceptions
By creating a new Exception class, programs can name their own exceptions. Exceptions should be typical of inheriting from the exception class, either directly or indirectly.
The following is an example of a runtimeerror-related instance in which a class is created and the base class is RuntimeError, which is used to output more information when the exception is triggered.
In the TRY statement block, after the user-defined exception executes the EXCEPT block statement, 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 follows:
Try
Raise Networkerror ("bad hostname")
Except Networkerror,e:
Print E.args