Python basics: detailed usage of try...except...

We put the statements that may cause errors in the try module, and use except to handle exceptions. except can handle a special exception or a group of exceptions in parentheses. If no exception is specified after except, all exceptions will be handled by default. Every try must have at least one except

1. The exception class can only handle specified exceptions, and cannot handle non-specified exceptions

s1 = 'hello'
try:
    int(s1)
except IndexError as e: # 未捕获到异常,程序直接报错
    print (e)

2. Multi-branch

s1 = 'hello'
try:
    int(s1)
except IndexError as e:
    print(e)
except KeyError as e:
    print(e)
except ValueError as e:
    print(e)

3. Universal exception Exception

s1 = 'hello'
try:
    int(s1)
except Exception as e:
    print(e)

4. Multi-branch + 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)

5. Other mechanisms for exceptions (try...finally syntax)

The try...finally statement will execute the final code regardless of whether an exception occurs.

The syntax is as follows:

try:
<语句>
finally:
<语句>    #退出try时总会执行
raise

Example:

'''
学习中遇到问题没人解答?小编创建了一个Python学习交流QQ群:725638078
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
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内代码块没有异常则执行我')
finally:
    print('无论异常与否,都会执行该模块,通常是进行清理工作')

6. Actively trigger an exception (raise statement)

We can use the raise statement to trigger exceptions by ourselves. The syntax format of raise is as follows:

raise [Exception [, args [, traceback]]]

Exception in the statement is the type of exception (for example, NameError) and the parameter is an exception parameter value. This parameter is optional, if not provided, the exception parameter is "None".

The last parameter is optional (rarely used in practice), and if present, is the trace exception object.

Example:

An exception can be a string, class or object. Most of the exceptions provided by the Python core are instantiated classes, which are parameters of an instance of a class.

Defining an exception is as simple as the following:

def functionName( level ):
    if level < 1:
        raise Exception("Invalid level!", level)
        # 触发异常后,后面的代码就不会再执行        
try:
    raise TypeError('类型错误')
except Exception as e:
    print(e)

7. Custom exceptions

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 BaseException. A class is created in the example, and the base class is BaseException, which is used to output more information when an exception is triggered.

In the try statement block, the except block statement is executed after the user-defined exception, and the variable e is used to create an instance of the Networkerror class.

class Networkerror(BaseException):
    def __init__(self,msg):
        self.msg=msg
    def __str__(self):
        return self.msg
 
try:
    raise Networkerror('类型错误')
except Networkerror as e:
    print(e)

8. Assertion: assert condition

assert 1 == 1 
assert 1 == 2

9. Summary try...except

  • Separate error handling from real work

  • The code is more organized and clearer, and complex work tasks are easier to implement

  • There is no doubt that it is safer, and the program will not crash unexpectedly due to some small negligence

At the end, I recommend a very good learning tutorial to everyone, I hope it will be helpful for you to learn Python!

Python basic tutorial recommendation: more Python video tutorials - pay attention to station B: Python learners

Python reptile case tutorial recommendation: more Python video tutorials - pay attention to station B: Python learners

Guess you like

Origin blog.csdn.net/qdPython/article/details/121539451