1, Types of anomalies In python, different exceptions can be identified with different types. An exception identifies an error.
1. Common exception classes AttributeError attempts to access a tree without an object, such as foo x. But foo has no attribute X IOError input / output abnormality; Basically, you can't open the file ImportError failed to import module or package; It's basically a path problem or a wrong name IndentationError syntax error (subclass of); code not aligned correctly IndexError subscript index exceeds the sequence boundary. For example, when x has only three elements, it attempts to access x[5] KeyError attempted to access a key that does not exist in the dictionary KeyboardInterrupt Ctrl+C pressed NameError uses a variable that has not been assigned to an object SyntaxError Python code is illegal and cannot be compiled (personally, I think this is a syntax error and wrong writing) TypeError the type of the incoming object does not match the required UnboundLocalError attempts to access a local variable that has not been set. Basically, you think you are accessing it because there is another global variable with the same name ValueError passes in a value that the caller does not expect, even if the value type is correct 2. Examples of exceptions:
# TypeError:int type cannot be iterated for i in 3: pass # ValueError num=input(">>: ") #Enter hello int(num) # NameError aaa # IndexError l=['egon','aa'] l[3] # KeyError dic={'name':'egon'} dic['age'] # AttributeError class Foo:pass Foo.x # ZeroDivisionError: unable to complete calculation res1=1/0 res2=1+'str'
2, Exception handling 1. Basic syntax try except
try: Detected code block except Exception type: try Once an exception is detected, the logic of this location is executed
give an example
try: f = [ 'a', 'a', 'a','a','a', 'a','a',] g = (line.strip() for line in f) #Tuple derivation print(next(g)) print(next(g)) print(next(g)) print(next(g)) print(next(g)) except StopIteration: f.close()
The exception class can only be used to handle the specified exception. If it is not specified, it cannot be handled.
s1 = 'hello' try: int(s1) except IndexError as e: # If no exception is caught, the program directly reports an error print(e)
2. Multi branch exception Exception and universal exception: exception
s1 = 'hello' try: int(s1) except IndexError as e: print(e) except KeyError as e: print(e) except ValueError as e: print(e) except Exception as e: print(e)
3,try/except...else The try/except statement also has an optional else clause. If this clause is used, it must be placed after all except clauses.
The else clause will be executed when no exception occurs in the try clause.
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()
4. The final execution of the exception is finally The try finally statement executes the last code whether or not an exception occurs.
Define cleanup behavior:
s1 = 'hello' try: int(s1) except IndexError as e: print(e) except KeyError as e: print(e) except ValueError as e: print(e) #except Exception as e: # print(e) else: print('try Execute if there is no exception in my code block') finally: print('The module is executed whether it is abnormal or not, usually for cleaning')
invalid literal for int() with base 10: 'hello'
The module is executed whether it is abnormal or not, usually for cleaning
3, Throw exception raise Python uses the raise statement to throw a specified exception.
The raise syntax format is as follows:
raise [Exception [, args [, traceback]]]
try: raise TypeError('Exception thrown, wrong type') except Exception as e: print(e)
The only argument 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 this throws an exception and don't want to deal with it, a simple raise statement can throw it again.
try: raise NameError('HiThere') except NameError: print('An exception flew by!') raise #An exception flew by! #Traceback (most recent call last): # File "", line 2, in ? #NameError: HiThere
4, Custom exception You can have your own exceptions by creating a new Exception class. The Exception class inherits from the Exception class and can be inherited directly or indirectly, for example:
In this example, the default init() of class Exception is overridden.
class EgonException(Exception): def __init__(self, msg): self.msg = msg def __str__(self): return self.msg try: raise EgonException('Exception thrown, wrong type') except EgonException as e: print(e)
Exception thrown, wrong type
1. Basic exception class When creating a module may throw many different exceptions, a common approach is to create a basic exception class for the package, and then create different subclasses for different error conditions based on this basic class:
Most exception names end with "Error", just like standard exception names.
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
5, assert assert is used to judge an expression and trigger an exception when the expression condition is false.
Assertions can directly return errors when the conditions are not met and the program runs without waiting for a crash after the program runs.
The syntax format is as follows:
assert expression
Equivalent to:
if not expression: raise AssertionError
assert can also be followed by parameters:
assert expression [, arguments]
Equivalent to:
if not expression: raise AssertionError(arguments)
The following example determines whether the current system is Linux. If the conditions are not met, an exception will be triggered directly without executing the next code:
import sys assert ('linux' in sys.platform), "This code can only be used in Linux Next execution"
Code to execute next # Traceback (most recent call last): # File "C:/PycharmProjects/untitled/run.py", line 2, in # Assert ('linux 'in sys. Platform), "this code can only be executed under Linux" # AssertionError: this code can only be executed under Linux