再看Exception in Python

  • Exceptions versus Syntax Errors

    Syntax errors occur when the parser detects an incorrect statement.

    Exception errors occurs whenever syntactically correct Python code results in an error.

  • Raising an Exception

    We can use raise to throw an exception if a condition occurs.

    if x > 5:
        raise Exception (f"x should not exceed 5")
    
  • The AssertionError Exception

    Instead of waiting for a program to crash midway, you can also start by making an assertion in Python.

    assert ("linux" in sys.platform), "This code runs on Linux Only."
    
  • The try and except Block: Handling Exceptions

    The try and except block in Python is used to catch and handle exceptions.

    Python executes code following the try statement as a “normal” part of the program.

    The code that follows the except statement is the program’s response to any exceptions in the preceding try clause.

    In the Python docs, you can see that there are a lot of built-in exceptions that you can use here.

    try:
        with open('file.log') as file:
            read_data = file.read()
    except FileNotFoundError as fnf_error:
        print(fnf_error)
    
  • The else Clause

    Using the else statement, you can instruct a program to execute a certain block of code only in the absence of exceptions.

    try:
        linux_interaction()
    except AssetionError as error:
        print(error)
    else:
        print("Executing the else clause.")
    
  • Cleaning up after using finally

    Imagine that you always had to implement some sort of action to clean up after executing your code。

    Python enables you to do so using the finally clause.

    扫描二维码关注公众号,回复: 13025846 查看本文章
  • Summing Up

    1. raise allows you to throw an exception at any time
    2. assert enables you to verify if a certain condition is met and throw an exception if it isn’t
    3. In the try clause, all statements are executed until an exception is encountered;
    4. except is used to catch and handle the exceptions that are encountered in the try clause;
    5. else lets you code sections that should run only when no exceptins are encountered in the try clause;
    6. finally enables you to execute sections of code that should always run, with or without any previously encountered exceptions;
  • References

  1. 廖雪峰的官方网站
  2. RealPython

猜你喜欢

转载自blog.csdn.net/The_Time_Runner/article/details/115261430
今日推荐