Get the App
SLTechnology News&Howtos  ›  Development  › 

What are the usage of exception handling in Python

Shulou Source: shulou.com Published: 2022-06-02 09:20:57 09月13日 Update

This article mainly explains "what are the uses of exception handling in Python". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "what are the uses of exception handling in Python?"

In order to ensure the robustness and fault tolerance of the program, that is, the program will not crash when an error is encountered, we need to handle the exception.

1.if to handle and prevent errors before they occur

If the condition under which the error occurs is predictable, we need to handle it with if to prevent the error before it occurs

AGE=10while True: age=input ('> >:'). Strip () if age.isdigit (): # the following code will not make an error only if age is an integer in the form of a string, if the predictable age=int (age) if age= = AGE: print ('you got it') break2. With try..except: handle after the error occurs

If the condition under which the error occurs is unpredictable, you need to use try..except: handle it after the error occurs

# basic syntax is try: detected code block except exception type: once an exception is detected in try For example # Python learning communication group: 725638078try: f=open ('a.txt') g = (line.strip () for line in f) print (next (g)) except StopIteration: f.close () so far, I believe you have a deeper understanding of "what is the use of exception handling in Python" You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Tags: Processing errors conditions learning code content programs detection robust practical deeper location interest only characters strings learning communication practicality practicality fault tolerance Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information Linux macOS NVidia Redmi