python-exception handling

Posted by mrdance on Sun, 04 Aug 2019 16:53:46 +0200

abnormal

  • Grammatical errors: space indentation grammatical rules
  • Logical Error Writing Code Implementation
    1. Conditional Judgment
    2. exception handling

Common anomalies

NameError

IndexError

TypeError

ValueError

Common anomalies

AttributeError attempts to access a tree that an object does not have, such as foo.x, but foo has no attribute x
 IOError input/output exception; basically unable to open file
 ImportError cannot introduce modules or packages; basically, it's a path problem or a name error
 Indentation Error grammar error (subclass); code not aligned correctly
 IndexError subscript index goes beyond the sequence boundary, for example, when x has only three elements and tries to access x[5]
KeyError attempts to access keys that do not exist in the dictionary
 Keyboard Interrupt Ctrl + C is pressed
 NameError uses a variable that has not been assigned to an object
 SyntaxError Python code is illegal and cannot be compiled.
TypeError incoming object type does not meet requirements
 UnboundLocalError attempts to access a local variable that has not yet been set, basically because there is another global variable with the same name.
Cause you think you're visiting it.
ValueError passes in a value that the caller does not expect, even if the value type is correct

More anomalies

ArithmeticError
AssertionError
AttributeError
BaseException
BufferError
BytesWarning
DeprecationWarning
EnvironmentError
EOFError
Exception
FloatingPointError
FutureWarning
GeneratorExit
ImportError
ImportWarning
IndentationError
IndexError
IOError
KeyboardInterrupt
KeyError
LookupError
MemoryError
NameError
NotImplementedError
OSError
OverflowError
PendingDeprecationWarning
ReferenceError
RuntimeError
RuntimeWarning
StandardError
StopIteration
SyntaxError
SyntaxWarning
SystemError
SystemExit
TabError
TypeError
UnboundLocalError
UnicodeDecodeError
UnicodeEncodeError
UnicodeError
UnicodeTranslateError
UnicodeWarning
UserWarning
ValueError
Warning
ZeroDivisionError

What is an exception?

When a program error occurs, the later code of the wrong program will not be executed.

What is exception handling?

It is designed to catch this exception (this code has nothing to do with program logic, but with exception handling). If it catches successfully, it enters another processing branch and executes the logic you customized for it so that the program does not crash. This is exception handling.

Why exception handling?

When a python parser detects an error, it triggers an exception. When the exception is triggered and not processed, the program terminates at the current exception. The code behind it will not run. Who will use a software that runs suddenly and crashes?

So you have to provide an exception handling mechanism to enhance the robustness and fault tolerance of your program.

Basic grammar for exception handling

Single branch

try:
     Code blocks detected
 Exceept except ion type:
     Once an exception is detected in try, the logic for this location is executed

test

try:
    f = open('test', 'r')
    lines = (line.strip() for line in f)
    print(lines.__next__())
    print(lines.__next__())
    print(lines.__next__())
    print(lines.__next__())
    print(lines.__next__())
except StopIteration:
    print("Ha-ha!")

#*********************************************
l = ['apple', 'banana', 'umbrella']
for num, goods in enumerate(l, 1):
    print(num, goods)
try:
    choose = int(input('Please enter the serial number of the goods you want to choose. :'))
    print(l[choose - 1])
except ValueError:
    print('Please enter a number.')

Multi-branch structure:

try:
     Code blocks detected
 Exceept except ion type:
     Once an exception is detected in try, the logic for this location is executed
 Exceept except ion type:
     Once an exception is detected in try, the logic for this location is executed
 Exceept except ion type:
     Once an exception is detected in try, the logic for this location is executed
...

test

l = ['apple','banana','umbrella']
for num,goods in enumerate(l,1):
    print(num,goods)
try:
    choose = int(input('Please enter the serial number of the goods you want to choose. :'))
    print(l[choose-1])
except ValueError:
    print('Please enter a number.')
except IndexError:
    print('The serial number you entered is not in the list of goods.')
l = ['apple', 'banana', 'umbrella']
for num, goods in enumerate(l, 1):
    print(num, goods)
try:
    choose = int(input('Please enter the serial number of the goods you want to choose. :'))
    print(l[choose - 1])
except (ValueError, IndexError):
    print('Please enter the correct and valid serial number.')
except NameError:
    print('One happened. name error')

Omnipotent anomaly

Almost all anomalies can be captured by omnipotent anomalies

try:
     Code blocks detected
except Exception: 
     Once an exception is detected in try, the logic for this location is executed
 # Or
try:
    Code blocks detected
except: 
Once an exception is detected in try, the logic for this location is executed

# But this is usually the case:
try:
     Code blocks detected
except Exception as e: 
     Once an exception is detected in try, the logic for this location is executed

test

try:
    a
    [][1]
    {}['key']
    1/0
    import aaa
except :
    print("No mistakes")
# **********************************************
try:
    a
    [][1]
    {}['key']
    1/0
    import aaa
except Exception :
    print("No mistakes")
#*********************************************
try:
    a
    [][1]
    {}['key']
    1/0
    import aaa
except Exception as e :
    print(e)
    print("No mistakes")

Note: try not to use the omnipotent exception, if you use, must write as

Multi-branch and omnipotent anomaly

l = ['apple', 'banana', 'umbrella']
for num, goods in enumerate(l, 1):
    print(num, goods)
try:
    choose = int(input('Please enter the serial number of the goods you want to choose. :'))
    print(l[choose - 1])
except (ValueError, IndexError):
    print('Please enter the correct and valid serial number.')
except Exception as e:
    print(e)

Note: Exception Universal Exceptions are always at the end of all except branches

summary

Single branch
try:
    Code that may have exceptions
 Exceept error type:
    Handling exceptions

Multi-branch
try:
    Code that may have exceptions
 Exceept error type 1:
    Handling exceptions
 Exceept error type 2:
    Handling exceptions

try:
    Code that may have exceptions
 except (Error Type 1, Error Type 2...):
    Handling exceptions

Omnipotent anomaly
try:
    Code that may have exceptions
except Exception as e:
    Handle exceptions and print or record e

Omnipotent anomaly and multi-branch
try:
    Code that may have exceptions
 Exceept error type 1:
    Handling exceptions
 Exceept error type 2:
    Handling exceptions
except Exception as e:
    Handle exceptions and print or record e

Extended grammar of exception handling

try:
    Code that may have exceptions
 except (Error Type 1, Error Type 2...):
    Handling exceptions
else:
    pass

test

l = ['apple','banana','umbrella']
for num,goods in enumerate(l,1):
    print(num,goods)

try:
    choose = int(input('Please enter the serial number of the goods you want to choose. :'))
    print(l[choose-1])
except (ValueError,IndexError) as e1:
    print(e1)
    print('Please enter a normal serial number.')
except Exception as e2:
    print(e2)
else:
    print('Execute me')

The above code: If there are no errors in the code block below try, the statement below else will be executed, and if there are errors in the code block below try, the corresponding exception statement will be executed.

Why not put the statement under else at the bottom of try's block? Look at the following code:

try:
    choose = int(input('Please enter the serial number of the goods you want to choose. :'))
    print(l[choose-1])
    print('Execute me')
except (ValueError,IndexError) as e1:
    print(e1)
    print('Please enter a normal serial number.')
except Exception as e2:
    print(e2)

If the code under else is placed under try, it can be said that the code is protected. When there are errors in the code under else, the corresponding exception handling will be performed. If there are no errors, it will be placed under try and under el, which is no difference at first sight.

finally

try:
    pass
except Error type 1:
    pass

except Error type 2:
    pass
...
finally:
    pass

test

l = ['apple', 'banana', 'umbrella']
for num, goods in enumerate(l, 1):
    print(num, goods)

try:
    choose = int(input('Please enter the serial number of the goods you want to choose. :'))
    print(l[choose - 1])
except (ValueError, IndexError) as e1:
    print(e1)
    print('Please enter a normal serial number.')
except Exception as e2:
    print(e2)
finally:
    print('Execute me')

# **********************************************
def func(filename):
    try:
        f = open(filename,'r')
        content = f.read()
        return content
    except Exception as e:
        print(e)
    finally:        # Execute it anyway
        f.close()
        print('It must be carried out.')

ret = func('test')
print(ret)


def wrapper(func):
    def inner(*args,**kwargs):
        try:
            print('before func')
            return func(*args,**kwargs)
        finally:
            print('after func')
    return inner

try:
    f = open('test')
    for line in f:
        a,b = line.strip().split(',')
finally:
    f.close()
    print('Execute me')

summary

  • Other: If there are no errors in the try code, execute it
  • finally: Must be implemented
    1. Execute the code in final before encountering return
    2. Encountering an error also executes the code in final before the end of the program

Exception handling structure:

# try except
# try except except
# try except ... else
# try except ... else finally
# try except ... finally
# try finally

Custom exception

class My_abnormal(Exception):
    def __init__(self, msg):
        self.msg = msg
        super().__init__()

    def __str__(self):
        return "abnormal{}".format(self.msg)  # Must be return or error will be reported
       

my_error = My_abnormal("NameError")
print(my_error)
class Empty(Exception):
    def __init__(self,msg):
        self.msg = msg
        super().__init__()
    def __str__(self):
        return self.msg

class class:
    def __init__(self):
        self.students = ['Tom']

    def get(self):
        if not self.students:
            raise Empty('The student list is empty')
        else:
            return self.students.pop()

clas = class()
stu1 = clas.get()
print(stu1)
stu2 = clas.get()
print(stu2)

throw

# exception types thrown by raise

Assertion

assert Boolean value
 # If true, the following code is executed smoothly
 # If false, throw an exception

Topics: PHP Python Attribute