A must-see for Python beginners: Python exception handling collection

abnormal

  • Errors in a broad sense are divided into errors and exceptions
  • Mistakes can be avoided
  • Anomaly refers to a problem that occurs under the premise of correct grammatical logic
  • In python, an exception is a class that can be handled and used

Abnormal classification

BaseException The base class of all exceptions

Exception base class for common errors

ArithmeticError The base class for all numerical calculation errors

Warning base class

AssertError assertion statement (assert) failed

AttributeError Attempt to access unknown object attribute

DeprecattionWarning Warning about deprecated features

EOFError User input file end flag EOF (Ctrl+d)

FloattingPointError floating point calculation error

FutureWarning A warning that the semantics of the structure will change in the future

When the GeneratorExit generator.close() method is called

ImportError when importing a module fails

IndexError Index is out of the range of the sequence

KeyError search for a non-existent keyword in the dictionary

KeyboardInterrupt user input interrupt key (Ctrl+c)

MemoryError Memory overflow (memory can be released by deleting the object)

NamerError tried to access a variable that does not exist

NotImplementedError method not yet implemented

OSError An exception generated by the operating system (for example, opening a file that does not exist)

OverflowError Numerical operation exceeds the maximum limit

OverflowWarning Old warning about automatic promotion to long integer (long)

PendingDeprecationWarning A warning that features will be abandoned

ReferenceError weak reference (weak reference) attempts to access an object that has been reclaimed by the garbage collection mechanism

RuntimeError General runtime error

RuntimeWarning Suspicious operating behavior (runtime behavior) warning

StopIteration iterator has no more values

SyntaxError Python's syntax error

SyntaxWarning Suspicious syntax warning

IndentationError Indentation error

TabError Tab and space mixed use

SystemError Python compiler system error

SystemExit Python compiler process is closed

TypeError invalid operation between different types

UnboundLocalError accesses an uninitialized local variable (a subclass of NameError)

UnicodeError Unicode-related errors (a subclass of ValueError)

UnicodeEncodeError Unicode encoding error (subclass of UnicodeError)

UnicodeDecodeError Unicode decoding error (subclass of UnicodeError)

UserWarning User code generated warning

ValueError passed an invalid parameter

ZeroDivisionError divide by zero

l = [1,2,3,4,5]
# 除零错误
num = int(input("Please input your num: "))
print(100/num)
Please input your num: 0
---------------------------------------------------------------------------

ZeroDivisionError                         Traceback (most recent call last)

<ipython-input-1-8abb196ce2aa> in <module>
      2 # 除零错误
      3 num = int(input("Please input your num: "))
----> 4 print(100/num)
ZeroDivisionError: division by zero

Exception handling

  • There is no guarantee that the program will always run correctly
  • However, it must be ensured that the problems obtained by the program in the worst case are properly managed
  • The entire syntax of python's exception handling module is:

try:

Try to achieve a certain operation,

If there are no exceptions, the task can be completed

If an exception occurs, throw the exception from the current code block to try to resolve the exception

except exception type 1:

Solution 1: Used to try to handle the exception here to solve the problem

 

except exception type 2:

Solution 2: Used to try to solve the problem by handling exceptions here

except (exception type 1, exception type 2...):

Solution: Use the same handling method for multiple exceptions

 

except:

If there are no exceptions, the code here will be executed

 

finally:

Is there any exception code to be executed

  • Process
  1. Execute the statement below try
  2. If an exception occurs, look for the corresponding exception in the except statement and handle it
  3. If there is no exception, execute the content of the else statement
  4. Finally, regardless of whether there is an exception, the finally statement must be executed

Many people learn python and don't know where to start.
Many people learn python and after mastering the basic grammar, they don't know where to find cases to get started.
Many people who have done case studies do not know how to learn more advanced knowledge.
So for these three types of people, I will provide you with a good learning platform, free to receive video tutorials, e-books, and the source code of the course!
QQ group: 705933274

  • Except except (at least one), else and finally are optional
# 简单异常案例
try:
    num = int(input("Please input your number:"))
    rst = 100/num
    print("计算结果是:{}".format(rst))
except:
    print("输入错误")
    # exit是退出程序的意思
    exit()

Please input your number:0
input error 

# 简单异常案例
# 给出提示信息
try:
    num = int(input("Please input your number:"))
    rst = 100/num
    print("计算结果是:{}".format(rst))
# 捕获异常后,把异常实例化,出错信息会在实例里
# 注意以下写法
# 以下语句是捕获ZeroDivisionError异常并实例化实例e
except ZeroDivisionError as e:
    print("输入错误")
    print(e)
    # exit是退出程序的意思
    exit()
# 简单异常案例
# 给出提示信息
try:
    num = int(input("Please input your number:"))
    rst = 100/num
    print("计算结果是:{}".format(rst))
# 如果是多种error的情况
# 需要把越具体的错误,越往前放
# 在异常类继承关系中,越是子类的异常,越要往前放,
# 越是父类的异常,越要往后放 、

# 在处理异常的时候,一旦拦截到某一个异常,则不再继续往下查看,直接进行下一个
# 代码,即有finally则执行finally语句,否贼就执行下一个大的语句
except ZeroDivisionError as e:
    print("输入错误")
    print(e)
    # exit是退出程序的意思
    exit()
except NameError as e:
    print("名字起错了")
    print(e)

except AttributeError as e:
    print("属性错误")
    print(e)
    exit()
# 常见错误的基类
# 如果写下面这句话,常见异常都会拦截住
# 而且下面这句话一定是最后一个excepttion
except Exception as e:
    print("我也不知道就出错了")
    print(e)

except ValueError as e:
    print("NO>>>>>>>>>>>")
print("hahaha")

 Please input your number:ffff
I don’t know it, it made an error
invalid literal for int() with base 10:'ffff'
hahaha

The user manually throws an exception

  • When in some cases, the user wants to raise an exception by himself, you can use
  • raise keyword to raise an exception
# raise 案例
try:
    print("I love you")
    print(3.1415926)
    # 手动引发一个异常
    # 注意语法:raise ErrorClassName
    raise ValueError
    print("还没完呀")
except NameError as e:
    print("NameError")
except ValueError as e:
    print("ValueError")
except Exception as e:
    print("有异常")
finally:
    print("我肯定会被执行的")

I love you
3.1415926
ValueError
I will definitely be executed 

# raise 案例-2
# 自定义异常
# 需要注意:自定义异常必须是系统异常的子类
class DanaValueError(ValueError):
    pass

try:
    print("I love you")
    print(3.1415926)
    # 手动引发一个异常
    # 注意语法:raise ErrorClassName
    raise DanaValueError
    print("还没完呀")
except NameError as e:
    print("NameError")
# except DanaValueError as e:
#    print("DanaError")
except ValueError as e:
    print("ValueError")
except Exception as e:
    print("有异常")
finally:
    print("我肯定会被执行的")

I love you 3.1415926 ValueError I will definitely be executed

# else语句案例

try:
    num = int(input("Please input your number:"))
    rst = 100/num
    print("计算结果是:{}".format(rst))
except Exception as e:
    print("Exceptiong")  
 
else:
    print("No Exception")
finally:
    print("反正我会被执行")

Please input your number:0

Exceptiong

I will be executed anyway

About custom exceptions

  • As long as it is a raise exception, a custom exception is recommended
  • When customizing an exception, it generally contains the following:
  • Customize the exception code where the exception occurs
  • Customize the problem prompt after an exception occurs
  • Customize the number of abnormal rows
  • The ultimate goal is to facilitate the programmer to quickly locate the error site once an exception occurs

I still want to recommend the Python learning group I built myself : 705933274. The group is all learning Python. If you want to learn or are learning Python, you are welcome to join. Everyone is a software development party and share dry goods from time to time (only Python software development related), including a copy of the latest Python advanced materials and zero-based teaching compiled by myself in 2021. Welcome friends who are in advanced and interested in Python to join!

 

Guess you like

Origin blog.csdn.net/m0_55479420/article/details/114836277