This is the sixth day of my participation in Gwen Challenge

Wechat public number search [program yuan xiaozhuang], pay attention to the halfway program yuan how to rely on Python development to support the family ~

preface

The running program does not know how to make the error, just did not handle the error, the program also terminated, is there any way to let the program error can not crash to continue to run? The answer is yes, through exception handling.

What is an exception

An exception, as the name implies, is abnormal. It is a signal that the program sends an error. Once an error occurs in the program, an exception will be generated. For example, the following program throws an exception:

>>> x
Traceback (most recent call last):  # Traceback: Trace backtracking exceptions
  File "<stdin>", line 1.in <module>  # Locate the exception
NameError: name 'x' is not defined  # NameError: The type of the exception
Copy the code

Anomalies fall into two general categories:

A SyntaxError is a low-level error that should be modified before the program runs

>>> if
  File "<stdin>", line 1
    if
      ^
SyntaxError: invalid syntax
Copy the code

The other is logical errors such as TypeError, NameError, IdenxError, and so on

# TypeError: Numeric and string types cannot be evaluated
1+ '2'# ValueError: type conversion error
num = input("> >")  # for example, type 'python'
int(num)

# NameError: references a nonexistent name x
x

# IndexError: The index exceeds the limit of the list
list1 = ['python'.'java']
l[3]

# KeyError: references a key that does not exist
dic={'name':'python'}
dic['age']

# AttributeError: The object attribute does not exist
class Test:
    pass
Foo.x
Copy the code

How to handle exceptions

To increase the robustness of your program, don’t terminate it even if something goes wrong during execution. Instead, the exception is caught and handled: the error message is logged.

Grammar mistakes

Errors in syntax must be corrected before the program runs.

if True  # SyntaxError: invalid syntax
	print('If branch does not add :')
Copy the code

A logical error

Logical errors are divided into two cases, one is the error of the conditions can be predicted, the other is the error of the conditions can not be predicted.

Error conditions in which an error can be predicted

If the error condition is predictable, it can be resolved by if judgment, for example:

age = 18
inp_age = input('> >').strip()
# It is predictable that strings and numbers cannot be compared in size
if inp_age.isdigit():
    inp_age = int(inp_age)
    if age > inp_age:
        print('bigger')
    else:
        print('error')
else:
    print('Please enter a number')
Copy the code

The conditions under which the error will occur are unpredictable

In the case of unpredictable error conditions, to ensure the reliability of the program, so that the program will not crash and terminate, it is necessary to deal with exceptions, the basic form of exception processing is as follows:

try: code that needs to be checked for exceptionsexceptException typesas e:  # as assigns the type of the exception to variable e. Print e to see the exact cause of the errorIf the code detects an exception, execute the code hereCopy the code

The following exception code can be handled with exception handling:

try:
    print('Exception check started')
    print(name)
    print('Exception check completed')
except NameError as e: 
    print(F prime is out of order{e}')
print('Program does not terminate, other code continues.')

# Result of the above code executionException check starts with exception name'name' is notDefined program does not terminate, other code continues executionCopy the code

If different types of exceptions are likely to occur in the checked code block, except with multiple branches can be used for different types of exceptions to handle them with different logic, similar to the multi-branch elIF, with the syntax as follows:

try: code that needs to be checked for exceptionsexceptNameError: Code executed when a NameError is detectedexceptKeyError: Code executed when a KeyError is detectedexcept. .Copy the code

For example:

def transfer_int(info) :
    
    try:
        res = int(info)
    except ValueErro as e:
        print(f'valueerror {e}')
        res = 'valueerror'
    except TypeError as e:
        print(f'typeerror {e})
        res = typeerror
    return res
              
transfer_info('python') # ValueError: invalid literal for int() with base 10: 'python'
transfer_int({'x': 1}) # TypeError: int() argument must be a string, a bytes-like object or a number, not 'dict'
Copy the code

If multiple exceptions want to be handled using the same logic, you can put multiple exceptions into a tuple and handle them with an EXCEPT branch.

try: code that needs to be checked for exceptionsexcept(NameError, ValueError, IndexError): Execute this code when three exceptions in a tuple occurCopy the code

A small partner has a question, do I need to run the program may appear in the abnormal need to write again, it is too much trouble. To make it easier for developers to handle exceptions, Python provides a universal Exception type, Exception, that can catch all exceptions:

try: code that needs to be checked for exceptionsexcept(NameError, ValueError, IndexError): Execute this code when three exceptions in a tuple occurexceptException: Use this logic when other types of exceptions occurCopy the code

For example:

print('start... ')

try:
    print('1111111111')
    l = ['aaa'.'bbbb']
    l[3] # Raise IndexError. Subsequent code of the same level will not run
    print('2222222222')
    xxx
    print('33333333')
    dic = {'a': 1}
    dic['aaa']
# except (IndexError, NameError) as e:
# print(' error: ', e)
# except KeyError as e:
# print(' dictionary key does not exist: ', e)
except Exception as e:  # universal anomaly
    print('All exceptions can be matched.')
print('end.... ')
Copy the code

Exception handling can be followed by an else, but else must be followed by except and cannot exist in a crude way. The code block under else is executed when the code to be checked does not raise any exceptions.

try:
    print('1111111111')
    l = ['1'.2]
    print('2222222222222')
    print(33333333333)
except IndexError as e:  # do not execute this code block, else will execute
    print('Exception message',e)

If there is no exception inside a try, else will be executed
else:
    print('I am the else')
Copy the code

In addition, try can also be used with finally. Finally must be followed by else, but the try-exception-finaally syntax can be used, or the try-finally format can be used directly, regardless of whether the code being tested is abnormal. Any code after finally will execute normally, so you can do some system resource reclamation, such as open files, ina finally code block.

print('start... ')

try:
    print('1111111111')
    l = ['aaa'.'bbbb']
    l[3] # Raise IndexError. Subsequent code of the same level will not run
    print('2222222222')
    xxx
    print('33333333')
    dic = {'a': 1}
    dic['aaa']
    f = open(r'a.txt'.'r', encoding='utf-8')
finally: No exception is handled, finally subcode is executed whether or not an exception occurs
    print('====》》》》》 should put the code that recycles system resources in the detected code here ')
    if f:
        f.close()

print('end.... ')
Copy the code

Raise – Manually triggered exceptions

For is not in conformity with the python interpreter syntax or the logic code, at runtime, the python interpreter will take the initiative to throw an exception, if in the program is running, a violation of the developers to customize various logic or rules, developers can also trigger the exception, you can use the -raise keywords manually trigger the exception, Raise must be followed by an exception class or the strength of the exception.

class Info() :
    
    def __init__(self, name) :
        if type(name) is not str:
            raise TypeError('name must be str')
        self.name = name
        
i = Info(123)  # # TypeError: name must be str
Copy the code

Usage scenarios of exception handling

In order to improve the robustness of programs, many beginners think that programs should be tried as much as possible. Except, this is a way of overusing exception handling and is not correct. It is recommended to use the if branch to determine the conditions that can be predicted that may trigger exceptions. Exception handling is performed only for some unpredictable conditions that are highly likely to trigger exceptions, such as network problems during download. In this case, exception handling can only be used.

conclusion

The article was first published on the wechat public account Program Yuan Xiaozhuang, and synchronized with nuggets and Zhihu.

The code word is not easy, reprint please explain the source, pass by the little friends of the lovely little finger point like and then go (╹▽╹)