05 Exception handling

Reprinted from Datawhale open source learning library

https://github.com/datawhalechina/team-learning-program/tree/master/PythonLanguage

Exception handling

Anomalies are errors detected during runtime. The computer language defines exception types for possible errors. When a certain error causes a corresponding exception, the exception handling program will be started to restore the normal operation of the program.

1. Python standard exception summary

  • BaseException: All abnormal base class
  • Exception: Conventional abnormality base class
  • StandardError: The base class for all built-in standard exceptions
  • ArithmeticError: The base class for all numerical calculation exceptions
  • FloatingPointError: floating point calculation exception
  • OverflowError : Numerical operation exceeds the maximum limit
  • ZeroDivisionError : division by zero
  • AssertionError : the assertion statement (assert) failed
  • AttributeError : Attempt to access unknown object attribute
  • EOFError: No built-in input, EOF mark reached
  • EnvironmentError: The base class of operating system exceptions
  • IOError: Input/output operation failed
  • OSError : An exception generated by the operating system (for example, opening a file that does not exist)
  • WindowsError: System call failed
  • ImportError : When importing a module fails
  • KeyboardInterrupt: user interrupt execution
  • LookupError: The base class for invalid data query
  • IndexError : Index is out of the range of the sequence
  • KeyError : Find a keyword that does not exist in the dictionary
  • MemoryError : memory overflow (memory can be released by deleting the object)
  • NameError : Attempt to access a variable that does not exist
  • UnboundLocalError: Access to uninitialized local variables
  • ReferenceError: Weak reference attempts to access objects that have been garbage collected
  • RuntimeError: General runtime exception
  • NotImplementedError: Method not yet implemented
  • SyntaxError : exception caused by syntax error
  • IndentationError: exception caused by indentation error
  • TabError: Tab and space are mixed
  • SystemError: General interpreter system exception
  • TypeError : invalid operation between different types
  • ValueError : Invalid parameter passed
  • UnicodeError: Unicode related exception
  • UnicodeDecodeError: exception during Unicode decoding
  • UnicodeEncodeError: exception caused by Unicode encoding error
  • UnicodeTranslateError: exception caused by Unicode conversion error

There are hierarchical relationships within the exception system. Some relationships in the Python exception system are as follows:


2. Python standard warning summary

  • Warning: The base class for warnings
  • DeprecationWarning: warning about deprecated features
  • FutureWarning: A warning that the semantics of the structure will change in the future
  • UserWarning: warning generated by user code
  • PendingDeprecationWarning: A warning that the feature will be deprecated
  • RuntimeWarning: warning of suspicious runtime behavior (runtime behavior)
  • SyntaxWarning: Suspicious syntax warning
  • ImportWarning: Used to trigger a warning during the import of a module
  • UnicodeWarning: warnings related to Unicode
  • BytesWarning: warnings related to bytes or bytecode
  • ResourceWarning: warnings related to resource usage

3. try-except statement

try:
    检测范围
except Exception[as reason]:
    出现异常后的处理代码

The try statement works as follows:

  • First, execute the tryclause ( the statement between the keyword tryand the keyword except)
  • If no exception occurs, the exceptclause is ignored , and the tryclause ends after execution.
  • If tryan exception occurs during the execution of the clause, the tryrest of the clause will be ignored. If the type of the exception exceptmatches the name after it, the corresponding exceptclause will be executed. tryThe code after the last executed statement.
  • If an exception does not match any except, then the exception will be passed to the upper layer try.

【example】

try:
    f = open('test.txt')
    print(f.read())
    f.close()
except OSError:
    print('打开文件出错')

# 打开文件出错

【example】

try:
    f = open('test.txt')
    print(f.read())
    f.close()
except OSError as error:
    print('打开文件出错\n原因是:' + str(error))

# 打开文件出错
# 原因是:[Errno 2] No such file or directory: 'test.txt'

A trystatement may contain multiple exceptclauses to handle different specific exceptions. At most only one branch will be executed.

【example】

try:
    int("abc")
    s = 1 + '1'
    f = open('test.txt')
    print(f.read())
    f.close()
except OSError as error:
    print('打开文件出错\n原因是:' + str(error))
except TypeError as error:
    print('类型出错\n原因是:' + str(error))
except ValueError as error:
    print('数值出错\n原因是:' + str(error))

# 数值出错
# 原因是:invalid literal for int() with base 10: 'abc'

【example】

dict1 = {
    
    'a': 1, 'b': 2, 'v': 22}
try:
    x = dict1['y']
except LookupError:
    print('查询错误')
except KeyError:
    print('键错误')
else:
    print(x)

# 查询错误

try-except-elseThe statement tried to query dicta key-value pair that was not in, which caused an exception. This exception should belong to exactly KeyError, but because it KeyErroris LookupErrora subcategory and will be LookupErrorplaced KeyErrorbefore it, the program executes the exceptcode block first. Therefore, when using multiple exceptcode blocks, you must adhere to the normative ordering, from the most targeted exception to the most general exception.

【example】

dict1 = {
    
    'a': 1, 'b': 2, 'v': 22}
try:
    x = dict1['y']
except KeyError:
    print('键错误')
except LookupError:
    print('查询错误')
else:
    print(x)

# 键错误

[Examples] a exceptclause can handle multiple exceptions that will be placed in a parenthesis as a tuple.

try:
    s = 1 + '1'
    int("abc")
    f = open('test.txt')
    print(f.read())
    f.close()
except (OSError, TypeError, ValueError) as error:
    print('出错了!\n原因是:' + str(error))

# 出错了!
# 原因是:unsupported operand type(s) for +: 'int' and 'str'

4. try-except-finally statement

try:
    检测范围
except Exception[as reason]:
    出现异常后的处理代码
finally:
    无论如何都会被执行的代码

Regardless of whether tryan exception occurs in the finallyclause , the clause will be executed.

If an exception tryis thrown in the clause without any exceptinterception, then the exception will be finallythrown after the clause is executed.

【example】

def divide(x, y):
    try:
        result = x / y
        print("result is", result)
    except ZeroDivisionError:
        print("division by zero!")
    finally:
        print("executing finally clause")


divide(2, 1)
# result is 2.0
# executing finally clause
divide(2, 0)
# division by zero!
# executing finally clause
divide("2", "1")
# executing finally clause
# TypeError: unsupported operand type(s) for /: 'str' and 'str'

5. try-except-else statement

If tryno exception occurs during the execution of the clause, Python will execute the elsestatement following the statement.

try:
    检测范围
except:
    出现异常后的处理代码
else:
    如果没有异常执行这块代码

exceptIt is not a good way to use it without any exception type. We cannot identify specific exception information through the program because it catches all exceptions.

try:
    检测范围
except(Exception1[, Exception2[,...ExceptionN]]]):
   发生以上多个异常中的一个,执行这块代码
else:
    如果没有异常执行这块代码

【example】

try:
    fh = open("testfile", "w")
    fh.write("这是一个测试文件,用于测试异常!!")
except IOError:
    print("Error: 没有找到文件或读取文件失败")
else:
    print("内容写入文件成功")
    fh.close()

# 内容写入文件成功

Note: elseThe existence of a exceptstatement must be based on the existence of exceptthe trystatement. Using a statement in a elsestatement without a statement will cause a grammatical error.


6. The raise statement

Python uses the raisestatement to throw a specified exception.

【example】

try:
    raise NameError('HiThere')
except NameError:
    print('An exception flew by!')
    
# An exception flew by!

Practice questions :

1. Guess the number game

Title description:

The computer generates a random number between zero and 100, and then asks the user to guess. If the number guessed by the user is larger than this number, the prompt is too large, otherwise the prompt is too small. When the user happens to guess, the computer will prompt, "Congratulations on guessing The number is...". Before the user guesses each time, the program will output the user's first guess, if the user input is not a number at all, the program will tell the user "input is invalid".

(Try to use try catch exception handling structure to handle the input situation)

Random module is used to obtain random numbers.

# your code here  

Practice personal solutions :

5 exercises

import random

i = 0
x = random.randint(0,100)

while(True):
    try:
        y = input('请输入一个0到100的整数:\n')
        y.isdigit() == True
        i = i + 1
        y = int(y)
        if y == x:
            print('You are right, the right number is {0}.\nThis is your {1}-th guess.'.format(x,i))
            break
        else:
            print('You are lose the competition, your answer is {0}, but the right answer is {1}\nThis is your {2}-th guess.'.format(y,x,i))
    except Exception:
        print('输入的数据不是正整数,请重新输入')
    

请输入一个0到100的整数:
 45


You are lose the competition, your answer is 45, but the right answer is 42
This is your 1-th guess.


请输入一个0到100的整数:
 双方都是


输入的数据不是正整数,请重新输入


请输入一个0到100的整数:
 4


You are lose the competition, your answer is 4, but the right answer is 42
This is your 3-th guess.


请输入一个0到100的整数:
 42


You are right, the right number is 42.
This is your 4-th guess.

Guess you like

Origin blog.csdn.net/Han_Panda/article/details/113092150
Recommended