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

Summary of Python basic exception handling

編輯:Python

Catalog

Preface

One 、 common Python abnormal

AssertionError: Assertions (assert) Failure

AttributeError: Trying to access unknown object properties

IndexError: Index out of range of sequence

KeyError: The dictionary looks for a keyword that does not exist

NameError: Try to access a variable that doesn't exist

OSError: An exception generated by the operating system

SyntaxError:Python A grammatical error of

TypeError: Invalid operation between different types

ZeroDivisionError: Divisor is zero.

Two 、try-except sentence

3、 ... and 、 Handle multiple exceptions in a unified way

Four 、 Catch all exceptions

5、 ... and 、try-finally sentence

6、 ... and 、raise sentence

7、 ... and 、 rich else sentence

8、 ... and 、 concise with sentence

Preface

We are human beings. , Often make mistakes , Programmers are no exception , Even experienced coders , There is no guarantee that the code you write will be 100% free of any problems . in addition , As a qualified programmer , Be aware of this when programming , That is never trust your users , So we should consider many aspects , The program written in this way will be more secure and stable .

So since the program always goes wrong , Then we need to use appropriate methods to solve the problem . An exception will be thrown if the program has a logic error or the user input is illegal , But these anomalies are not fatal , Will not cause the program to crash , You can use Python Provided exception handling mechanism , Catch the exception in time , And digest it from the inside .

So what is an exception ? for instance :

This assumes, of course, that the user's input is correct , But as long as the user enters a file name that does not exist , So the above code is vulnerable :

The above example throws a FileNotFoundError abnormal , that Python What other exceptions might be thrown , Let's introduce some common exceptions , In this way, you will not feel strange when you encounter such an exception in the future .

One 、 common Python abnormal AssertionError Assertions (assert) Failure

Assertion statements have been covered in previous chapters on branching and looping (assert), When assert When the condition after this keyword is false , The program will terminate and throw AssertionError abnormal .assert Statements are generally used to place checkpoints in code when testing programs :

AttributeError: Trying to access unknown object properties

Exception thrown when the object property you are trying to access does not exist :

IndexError: Index out of range of sequence

When using sequences, we often encounter IndexError abnormal , as a result of Index contents beyond the range of the sequence

KeyError: The dictionary looks for a keyword that does not exist

When An attempt to find a keyword that does not exist in the dictionary will result in KeyError abnormal , Therefore, it is recommended to use dict.get() Method

NameError: Try to access a variable that doesn't exist

When Try to access a variable that doesn't exist when ,Python Will throw out NameError abnormal :

OSError: An exception generated by the operating system

OSError As the name suggests, it is an exception produced by the operating system , Like opening a nonexistent file will cause FileNotFoundError, And this FileNotFoundError Namely OSError Subclasses of . The above example has already demonstrated , I won't go into that here .

SyntaxError:Python A grammatical error of

If encounter SyntaxError yes Python A grammatical error of , At this time Python The code for cannot continue to execute , You should find and correct your mistakes :

TypeError: Invalid operation between different types

Some types are different and cannot be calculated with each other , Otherwise it will throw TypeError abnormal :

ZeroDivisionError: Divisor is zero.

We all know Divisor cannot be zero , So dividing by zero causes ZeroDivisionError abnormal :

Two 、try-except sentence

try-except The statement format is as follows :

try:
Detection range
except Exception[as reason]:
Something unusual happened (Exception) Post processing code

try-except Statement is used to detect and handle exceptions , Give an example of how this all works .

We also introduced , When the file to be opened does not exist , Will trigger FileNotFoundError, Obviously, the user experience is not good , So we can modify it like this :

The result is :

The above example uses the usual language to describe the error message , The user experience will be much better .

But from a programmer's point of view , Lead to OSError There are many reasons for anomalies ( for example FileNotFoundError、FileExistsError、PermissionError etc. ), So you may be more concerned about the specific content of the error , Here you can. Use as Print out specific error messages

The implementation result is :

Set multiple... For different exceptions except

One try Statements can be combined with multiple except The statement is tie-in , Detect and process the interested anomalies respectively :

3、 ... and 、 Handle multiple exceptions in a unified way

except Multiple exceptions can follow , And then we can deal with these exceptions in a unified way :

Four 、 Catch all exceptions

If you are not sure what kind of exception to handle , It's just hope that try Once any exception occurs in the statement block , You can give users a “ I can read it ” Reminder , So we can do that :

5、 ... and 、try-finally sentence

Here's an example , If "a.txt" Do exist ,open() Function can return the file object normally , However, the exception occurs after the file is opened sum = 1 + ‘1’ On statement , here Python Will jump directly to except sentence , in other words , The file is open , But the command to close the file is not executed :

In order to achieve this “ Even if something goes wrong , But it also has to do the finishing work ( For example, saving user documents before a program crashes )”, Introduced finally To expand try:

If try In the block No runtime errors have occurred , Will skip except Statement execution finally The content of the statement block .
If Something unusual happened , It will be executed first except The contents of the statement block are executed again finally The content of the statement block .
All in all ,finally The content in a statement block is what ensures that it will be executed anyway .

6、 ... and 、raise sentence

Some readers may think , Can my code throw an exception by itself ? The answer is yes , You can Use raise Statement throws an exception

The exception thrown is OK With parameters , Express An abnormal explanation

7、 ... and 、 rich else sentence

For most programming languages ,else Statements can only follow if The statement is tie-in , But in Python in ,else The function of the statement is more abundant . stay Python in ,else sentence Not only with if Sentence construction , It's like a loop statement (for Sentence or while sentence ) collocation , I can also tell you what I just said Exception handling .

1、 Typical if-else sentence

if Conditions :
The condition is true execution
else:
The condition is false execution

2、else And for and while Loop statement collocation

for instance :

This program is mainly to find the maximum divisor of the number entered by the user , If it is a prime number, it will remind you that it is a prime number .
The methods of using violence are tried one by one (num%count==0), If the conditions are met, print out the largest divisor , and break, At the same time, it will not execute else The content of the statement block . But if the right conditions have not been met , Will perform else Statement block content .

for Sentence usage and while The sentence is the same , I won't go into details here .

3、else Statement with exception handling

else Statement can also be used with exception handling just mentioned , as long as try There are no exceptions in the statement block , Then it will carry out else The contents of the statement block .

for instance :

8、 ... and 、 concise with sentence

Some readers feel that opening and closing a file , It's a bit troublesome to pay attention to exception handling , therefore Python Provides a with sentence , Use this statement to abstract the frequently used try/except/finally Relevant details , Use... For file operations with sentence , Will greatly reduce the amount of code .

for instance :

Use with sentence , I could change it like this :

With with sentence , No longer have to worry about forgetting to close the file .

This is about Python This concludes the article on basic exception handling , More about Python Please search the previous articles of SDN or continue to browse the related articles below. I hope you will support SDN more in the future !



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