程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python learning - Chapter 8 errors and exceptions

編輯:Python

introduction

In the previous study , We came across a lot of wrong information , This article will introduce these mistakes

Grammar mistakes

When we execute the program , It is found that the error message is "SyntaxError" At the beginning , It means that this is a grammatical error , At the same time, the compiler will determine which file the error occurs in 、 The first few lines and characters that start to go wrong are clearly marked , At this point, we only need to search and modify

abnormal

Even if Python Your grammar is correct , However, some unexpected errors will occur at runtime , The error detected by the runtime is an exception , Some errors may not be fatal, but if the program does not handle most exceptions , The compiler prints the error to the screen and terminates the program , The compiler will throw "Traceback" Used to indicate that an exception has occurred , And then indicate what kind of mistake it is , Different exceptions will have different exception names output

Common problems are as follows
Divide by zero error "ZeroDivisionError"

Variable undefined error "NameError"

str The type and int Type concatenation error "TypeError"

No related key error in dictionary type "KeyError"

Index out of range error "IndexError"

Of course, there are many exception types , You can consult the official documents by yourself

exception handling

Sometimes the occurrence of an anomaly is unexpected , When an exception occurs, the program will abort , Even if this exception does not affect the integration program or subsequent programs , At this point, we need to handle the exception to make the program continue , So as not to terminate the whole program , Below we will describe an example for easy understanding

while True:
number = int(input(" Please enter a number "))

This example will allow the user to continuously input content ( Press down Ctrl+C The key combination of can stop the program ), The program will continue as the user enters numbers , But when the user enters a non number , for example "abc" The program will output an error and exit , But in the actual experience, we can't meet what the user's input is , For example, we are on a mobile phone APP Some illegal entries are entered in the... At this time APP Automatically quit , This is definitely not a good experience , We need to handle these exceptions , Make sure that the program does not exit because of these exceptions

while True:
try:
number = int(input(" Please enter a number "))
except ValueError:
print(" I'm afraid the number you entered is not a valid number , Please re-enter ")

At this point when our try The input in the method throws ValueError The question is , Will execute except ValueError: The statement in
Here we use two new keywords :try and except, These two keywords are used to catch exceptions and let us run the corresponding code to handle exceptions , The grammar is as follows

try:
Business grammar block
except Exception types :
Handling exception syntax blocks

stay try Business grammar block , Any exceptions generated will terminate the business syntax block and jump to except Match exception types , If there is a match, the syntax block that handles the exception will be run , Otherwise, the program will exit with an error

while True:
try:
number = int(input(" Please enter a number "))
except KeyError:
print("KeyError")
except ValueError:
print("ValueError")
except KeyboardInterrupt:
print(" User termination , Exit procedure ") # Ctrl+C Will throw such an exception 
exit()
except Exception as e:
print(" Unknown error ",e)

Because most exceptions are inherited from Exception The parent class , So the matching exception is Exception You can always match most exceptions

Throw an exception

All of the above are exceptions thrown by the system , Of course, we can also throw exceptions manually , have access to raise Statement to manually throw a specified exception

raise Exception

This example outputs an exception without any content , The error message is empty , We can also specify to output an error content exception

raise Exception(" This is an error message ")

This example will give an error message when throwing an exception , We can use this method to prompt the user when manually throwing an exception , Where did the program go wrong

finally sentence

finally The statement needs and try Statement together , Its function is whether there are exceptions or whether exceptions are caught ,finally Statements are guaranteed to execute

try:
print(1/0)
except ZeroDivisionError:
print(" Abnormal division by zero ")
finally:
print("finally Clause ")

The results are as follows

 Divide by zero error
finally Clause

This feature is very useful in future database and file processing , Because both database and file processing , After doing some operations, you need to do some necessary remedial work

Custom exception

Custom exceptions should inherit from Exception class , You can inherit directly or indirectly , When we use raise When a user-defined exception is thrown, the system will receive the exception and output our predetermined error message , Of course we can use it except Catch this custom exception

class MyException(Exception):
def __init__(self):
pass
def __str__(self):
return " This is a custom exception "
def raise_customer_exception():
raise MyException()
try:
raise_customer_exception()
except MyException as e:
print("Error",e)

The results are as follows

Error This is a custom exception

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved