Python -- exception handling

Posted by zmoerf on Wed, 19 Jan 2022 12:42:10 +0100

As a python beginner, I want to write a blog to record my growth process and share what I have learned. The following are some superficial views and personal understanding of Python language by a python beginner.

#try... An except structure
'''
try... except is the most common exception handling structure. The structure is as follows:
try:
Monitored statement blocks that may throw exceptions
except BaseException [as e]
Exception handling statement block

The try block contains code that may throw exceptions, and the exception block is used to catch and handle exceptions. During execution, if no exception is thrown in the try block, skip the except block and continue to execute subsequent code; When executing, if
If an exception occurs in the try block, skip the subsequent code in the try block and jump to the corresponding except block to handle the exception; After exception handling, continue to execute subsequent codes
'''

print("step0")
try:
    print("step1")
    a = 3/0
    print("step2")
except BaseException as e:
    print("step3")
    print(e)
    print(type(e))
print("end")

#try... Multiple exception structures
'''
It is generally required to catch multiple exceptions that may occur (in the order of subclass first and then parent class) and write exception handling code targeted. To avoid missing possible exceptions, you can add BaseException at the end
try:
Monitored statement blocks that may throw exceptions
except Exception1:
Statement block handling Exception1
except Exception2:
Statement block handling Exception2
...
except BaseException:
A statement block that handles exceptions that may be missing

'''

try:
    a = input("Please enter a divisor:")
    b = input("Please enter a divisor:")
    c = float(a) / float(b)
    print(c)
except ZeroDivisionError:
    print("Exception, cannot divide by 0")
except ValueError:
    print("Exception, cannot convert string to number")
except NameError:
    print("Exception, variable does not exist")
except BaseException as e:
    print(e)

#try... except... else structure
'''
Try... Except... Else structure adds "else block". If no exception is thrown in the try block, the else block is executed. If an exception is thrown in the try block, the except block is executed instead of the else block
'''

try:
    a = input("Please enter a divisor:")
    b = input("Please enter a divisor:")
    c = float(a)/float(b)
except BaseException as e:
    print(e)
else:
    print(c)
print("Program end")

#try... except... finally structure
#In the try... except... Finally structure, the finally block will be executed regardless of whether an exception occurs; It is usually used to release the resources requested in the try block

try:
    a = input("Please enter a divisor:")
    b = input("Please enter a divisor:")
    c = float(a)/float(b)
except BaseException as e:
    print(e)
else:
    print(c)
finally:
    print("I am finally The statements in are executed regardless of whether an exception occurs or not")
print("Program end")

#return statement and exception handling
#Return has two functions: ending method operation and returning value. We generally don't put return in the exception handling structure, but at the end of the method

def test01():
    print("step1")
    try:
        x = 3/0
    except:
        print("step2")
        print("Exception: 0 cannot be divisor")
    finally:
        print("step4")
    print("step5")
    return e

print(test01())

#trackback module
#Use the Traceback module to print exception information

import traceback
try:
    print("step1")
    num = 1/0
except:
    traceback.print_exc()

#Custom exception class
#In program development, sometimes we need to define Exception classes ourselves. Custom Exception classes are generally run-time exceptions, which usually inherit Exception or its subclasses. Generally, Error and Exception are used as suffixes
#Custom exceptions are actively thrown by raise statements

class AgeError(Exception):  #Inherit Exception
    def __init__(self,errorInfo):
        Exception.__init__(self)
        self.errorInfo = errorInfo
    def __str__(self):
        return str(self.errorInfo)+",Wrong age! It should be at 1-150 between"
################Test code######################
if __name__ == '__main__':     #If True, the module runs as a separate file and can execute test code
    age = int(input("Enter an age:"))
    if age<1 or age>150:
        raise AgeError(age)
    else:
        print("Normal age:",age)

#Loop in numbers, and handle exceptions if they are not numbers. If you enter 88, the cycle ends

while True:
    try:
        x = int(input("Please enter a number"))
        print("Number entered:",x)
        if x == 88:
            print("Exit program")
            break
    except BaseException as e:
        print(e)
        print("Exception, the input is not a number")
print("End of cyclic digital input program")

Topics: Python Back-end