Exception handling for python

An error and exception

1. What is an error

Friends who are programmed should be familiar with programming errors, but what are them? Looking at some articles, I think the description below is more nice. First, there are two types of errors, as follows

  • Syntax Errors: Code written does not conform to the syntax of the interpreter or compiler, such as improper indentation in python, missing colons, misspelling, etc.
#Indentation error
for i in range(10):
print(i)

#Colon missing error
for i in range(10)
    print(i)

  • Logical error: incomplete, illegal input, calculation error, etc.
#Logical error
re = 3 / 0
print(re)

2. What is an exception

There are also two types of anomalies, as follows

  • First, there are no errors in the program syntax, but logic or algorithm problems are encountered during execution.
  • Second, the program runs in the process of computer exceptions, such as insufficient memory, IO errors

3. Differences between errors and exceptions

Errors are grammar or logic errors that occur before a program is run. Grammar errors can be modified before the program is executed, but logic errors cannot be modified.

Exceptions are divided into two steps, one is the generation of exceptions, the interpreter detects errors and considers them exceptions, throwing exceptions; The second is the handling of exceptions, intercepting exceptions, ignoring or terminating programs.

The following are from Baidu:
From the software point of view, errors are syntax or logic problems. Grammar errors indicate structural errors in the software that cannot be interpreted by the interpreter or compiled by the compiler. These errors must be corrected before the program is executed. When the program syntax is correct, all that remains is a logical error, which may be caused by incomplete or illegal input or, in other cases, by a process that logic cannot generate, calculate, or output the results of which it requires, which cannot be executed. These errors are often referred to as domain errors and scope errors, respectively.
When Python detects an error, the interpreter indicates that execution is no longer possible, and an exception occurs.
Exceptions are behaviors taken outside the normal control flow because of errors in the program. This behavior is divided into two phases: the first is the error that caused the exception, and the second is the detection phase.

The first phase occurs after an exception condition occurs, and whenever an error is detected and an exception condition is recognized, the interpreter raises an exception, which can also be called a trigger or build, through which the interpreter notifies the current control flow that an error has occurred.

Python also allows programmers to throw exceptions themselves, either by the Python interpreter or by the programmer. Exceptions are signals that errors occur. The current stream is interrupted to handle the error and take appropriate action. This is the second stage.

Processing of exceptions occurs in the second stage. When an exception is raised, many different actions can be called, either to ignore the error or to try to continue executing the program after mitigating the impact of the problem. All these actions represent a continuation or a branch of control. The key is that the programmer can indicate how the program will perform when the error occurs.

Exception handling module for two python s

The main exception handler for python is the try...except...statement block, which is subdivided as follows

1. try...except

try:
	Code with exceptions
except:
	Code to execute after an exception occurs

The execution logic of try...except is as follows

  • 1 Execute the code between try and except first. If the code is working properly and no exceptions are thrown, ignore the code after except and try...except runs to the end.
  • 2 If the code execution between try and except throws an exception, the exception thrown matches the type of exception except will handle, then the code after except is executed
  • 3 If a code throw exception between the execution of try and except does not match the exception that except will handle, the exception is thrown back into try.
#try...except code block
#Code works correctly after try, ignoring except
try:
    a, b = 2, 2
    print(a / b)
except ZeroDivisionError as err:
    print("The error message is as follows:", err)

#try...except code block
#Code error after execution of try, except handles exception
try:
    a, b = 2, 0
    print(a / b)
except ZeroDivisionError as err:
    print("The error message is as follows:", err)


However, there are two points to note:

  • A try can then branch to multiple except s, with at most one executed
  • An except can handle multiple exception types, matching one after the other
#Multiple except branches
try:
    with open("test.txt", 'r') as f:
        file = f.read()
        msg = int(file)
except OSError as err:
    print("The error message is as follows:", err)
except TypeError as err:
    print("The error message is as follows:", err)

#One except handles multiple exceptions
try:
    with open("test1.txt", 'r') as f:
        file = f.read()
        msg = int(file)
except (OSError, ValueError) as err:
    print("The error message is as follows:", err)

2. try...except...else

try:
	Code with exceptions
except:
	Code to execute after an exception occurs
else:
	Code to execute when no exception occurs

Try...except...else statement: the else statement is placed after all excepts, because the else is executed when there is no error in the execution of the code inside the try. If a try error is executed, the else will not be executed. as follows

#try...except...else statement
try:
    file = open("mytest.txt", 'r')
except IOError as err:
    print("Error opening file:", err)
else:
    #When the file opens normally, execute the following code
    msg = file.read()
    print(msg)

The mytest.txt file does not exist, catches exceptions, and does not execute else

Open the existing test.txt file and execute an else statement to read the contents

#try...except...else statement
try:
    file = open("test.txt", 'r')
except IOError as err:
    print("Error opening file:", err)
else:
    #When the file opens normally, execute the following code
    msg = file.read()
    print(msg)

3. try...except...finally

try:
	Code with exceptions
except:
	Code to execute after an exception occurs
else:
	Code to execute when no exception occurs
finally:
	Code to execute with or without exceptions

else is executed when there are no exceptions for the code to execute after try execution, while finally is executed no matter there are no exceptions for try execution, as follows

#try...finally statement
try:
    a, b = 1, 0
    res = a / b
except ZeroDivisionError as err:
    print("Please check the input:", err)
else:
    print("Input validity check passed...")
    print("The results are as follows:", res)
finally:
    print("The number you entered is:", a, b)

Enter divisor 0, no else, finally

Enter normal, execute else and finally

#try...finally statement
try:
    a, b = 1, 2
    res = a / b
except ZeroDivisionError as err:
    print("Please check the input:", err)
else:
    print("Input validity check passed...")
    print("The results are as follows:", res)
finally:
    print("The number you entered is:", a, b)


Tri raise throws an exception

Python not only catches and throws exceptions on its own, but also lets the programmer specify to throw exceptions on his own. Using the keyword raise in python, you can throw a specified exception with the following syntax format

raise Exception(Exception Description)
#Parameter Interpretation
Exception: An exception class name or Exception
#Use raise to throw an exception if the input is not all numbers
num = '123ghf'
def number():
    #Determine if the string is all numbers
    in_str = num.isdigit()
    if in_str == False:
        raise Exception('Input is illegal, please re-enter')
    else:
        return int(num)
num = number()
print(num)


All inputs are numbers, no raise exceptions

#Use raise to throw an exception if the input is not all numbers
num = '123456'
def number():
    #Determine if the string is all numbers
    in_str = num.isdigit()
    if in_str == False:
        raise Exception('Input is illegal, please re-enter')
    else:
        return int(num)
num = number()
print(num)

Four custom exceptions

In addition to python's built-in exception classes, we can customize our own exceptions, which inherit directly or indirectly from the Exception class when we customize it.

#Custom Exception
class MyLengthException(Exception):
    def __init__(self, length):
        self.length = length

#Validate input length, throw MyLengthException exception if not met
try:
    low_limit, higth_limit = 6, 12
    pwd = input("Please enter your password:")
    if len(pwd) < 6 or len(pwd) > 12:
        raise MyLengthException(len(pwd))
except MyLengthException as err:
    print("Illegal password length entry, please re-enter the 8 to 12 digit password")
else:
    print("Your password is:{} Please confirm".format(pwd))


Input length does not meet requirements

Keywords: Python

Added by knashash on Sun, 07 Nov 2021 18:38:20 +0200