Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Analyze Python exception handling

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article focuses on "analyzing Python exception handling". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "analyzing Python exception handling".

"you can't always be right."

Even computers can make mistakes. Of course, programmers are no exception, even experienced programmers can not guarantee that the code written is 100% free of any problems (otherwise there are so many loopholes).

Logic errors in the program or illegal user input will throw exceptions, but these events are not fatal and will not lead to program necrosis. The exception handling mechanism provided by Python can be used to catch the exception in time and digest it internally.

Then the next step is to learn Python's posture correctly.

So what is abnormal? Let's first learn that if you write an exception code, after running, an exception occurs, the code stops, and a Traceback is displayed, which contains a report on the exception, for example:

# example1.py

File_name = 'non-existent file .txt'

F = open (file_name,'r')

Print ('output file contents:')

For line in f:

Print (line)

Here is to open a file that does not exist, so this will cause an exception in the code:

Traceback (most recent call last):

File "E:/PycharmProjects/untitled2/abnormal/example1.py", line 2, in

F = open (file_name,'r')

FileNotFoundError: [Errno 2] No such file or directory: 'any file .txt'

The above example throws a FileNotFoundError exception.

Of course, Python can't just throw such an exception.

What exceptions does Python usually throw? Here I first list one by one, make a summary, let you have an understanding first, so that when you encounter such an anomaly in the future, you will not feel strange.

Summary of common anomalies

1. FileNotFoundError: file exception not found

A common problem with using files is that they cannot be found: the file you are looking for may be somewhere else, the file name may be incorrect, or the file may not exist at all.

Having given an example above, I will not give any more examples here.

2. AssertionError: assertion statement (assert) failed

When the condition after the assert keyword is false, the program will stop and throw an AssertionError exception. Assert statements are typically used to place checkpoints in the code when testing the program:

# example2

My_list = ['example2']

Assert len (my_list) > 0

My_list.pop ()

Assert len (my_list) > 0

Exception:

Traceback (most recent call last):

File "E:/PycharmProjects/untitled2/abnormal/example.py", line 5, in

Assert len (my_list) > 0

AssertionError

3. AttributeError: attempt to access unknown object properties

An AttributeError exception is thrown when the object property you are trying to access does not exist:

# example3

My_list = []

My_list.example3

Exception:

Traceback (most recent call last):

File "E:/PycharmProjects/untitled2/abnormal/example.py", line 2, in

My_list.example3

AttributeError: 'list' object has no attribute' example3'

4. IndexError: the index is out of the sequence range

You often encounter IndexError exceptions when using sequences because you index content that is out of range of the sequence:

# example4

My_list = [1pm 2pm 3]

X = my_list [3]

Print (x)

Exception:

Traceback (most recent call last):

File "E:/PycharmProjects/untitled2/abnormal/example.py", line 2, in

X = my_list [3]

IndexError: list index out of range

5. KeyError: look for a keyword that does not exist in the dictionary

A KeyError exception is thrown when trying to find a keyword that does not exist in the dictionary, so it is recommended to use the dict.get () method:

# example5

My_dist = {'one':1,' two':2, 'three':3}

X = my_dist ['one']

Print (x)

Y = my_dist ['four']

Print (y)

Exception:

one

Traceback (most recent call last):

File "E:/PycharmProjects/untitled2/abnormal/example.py", line 4, in

Y = my_dist ['four']

KeyError: 'four'

6. NameError: try to access a variable that does not exist

When trying to access a variable that does not exist, Python throws a NameError exception:

# example6

Example6

Exception:

Traceback (most recent call last):

File "E:/PycharmProjects/untitled2/abnormal/example.py", line 1, in

Example6

NameError: name 'example6' is not defined

7. OSError: exceptions generated by the operating system

OSError, as its name implies, is an exception generated by the operating system, just like opening a file that does not exist will throw FileNotFindError, and this FileNotFindError is a subclass of OSError.

The example has been demonstrated above, so I won't repeat it here.

8. Syntax error of SyntaxError:Python

If you encounter that SyntaxError is a syntax error of Python, and the Python code cannot continue to execute, you should first find and correct the error:

# example8

Print'I am example8'

Exception:

File "E:/PycharmProjects/untitled2/abnormal/example.py", line 1

Print'I am example8'

^

SyntaxError: Missing parentheses in call to 'print'. Did you mean print ('I am example8')?

9. TypeError: invalid operation between different types

Objects of different types cannot evaluate each other, otherwise a TypeError exception will be thrown:

# example9

X = 1 +'1'

Print (x)

Exception:

Traceback (most recent call last):

File "E:/PycharmProjects/untitled2/abnormal/example.py", line 1, in

X = 1 +'1'

TypeError: unsupported operand type (s) for +: 'int' and' str'

10. ZeroDivisionError: divisor is zero

Everyone knows that the divisor is not zero, so dividing by zero throws a ZeroDivisionError exception:

# example10

X = 365 / 0

Print (x)

Exception:

Traceback (most recent call last):

File "E:/PycharmProjects/untitled2/abnormal/example.py", line 1, in

X = 365 / 0

ZeroDivisionError: division by zero

Now that we have finished talking about the common types of exceptions, let's get to the point of how to handle exceptions.

I. try-except statement

1. Grammatical structure:

Try:

Test content

Except Exception [as reason]:

Handling code after an exception (Exception) occurs

two。 Take a simple example:

# example

F = open ('non-existent document .txt')

Print (f.read ())

F.close ()

When the document .txt that does not exist in the above example does not exist, Python will report an error and an exception:

Traceback (most recent call last):

File "E:/PycharmProjects/untitled2/abnormal/example.py", line 1, in

F = open ('non-existent document .txt')

FileNotFoundError: [Errno 2] No such file or directory: 'documents that do not exist .txt'

At this point, to solve the exception problem, we can modify the code as follows:

Try:

F = open ('non-existent document .txt')

Print (f.read ())

F.close ()

Except OSError:

Print ('error opening file Trout')

Give it a try:

There was an error opening the file, Taper.

Note: the reason why I use OSError instead of FileNotFindError here is that there are many reasons for OSError exceptions (such as FileNotFindError,FileExistsError,PermissionError, etc.)

Of course, if you care more about the specific content of the error, you can use as to print out the specific error message:

Try:

F = open ('non-existent document .txt')

Print (f.read ())

F.close ()

Except OSError as reason:

Print ('an error occurred while opening the file. The reason for the error is:'+ str (reason)).

After running, the result is:

There was an error opening the file, Taper.

The reason for the error is: [Errno 2] No such file or directory: 'non-existent document.txt'

3. Set multiple except for different exceptions

A try statement can be matched with multiple except statements (the disadvantage is that it only returns the first exception found):

# example

Try:

X = 1 +'1'

F = open ('non-existent document .txt')

Print (f.read ())

F.close ()

Except OSError as reason:

Print ('an error occurred while opening the file. The reason for the error is:'+ str (reason)).

Except TypeError as reason:

Print ('Type error\ nThe error is caused by:' + str (reason))

After running, the result is:

The type is wrong, Taper.

The error is caused by: unsupported operand type (s) for +: 'int' and' str'

4. Unified handling of multiple exceptions

Except can be followed by multiple exceptions, and then handle these exceptions uniformly (also the disadvantage is that it only returns the first discovered exception):

Try:

Int ('abc')

X = 1 +'1'

F = open ('non-existent document .txt')

Print (f.read ())

F.close ()

Except (OSError, TypeError, ValueError) as reason:

Print ('error tint\ nThe reason for the error is:' + str (reason))

After running, the result is:

Which hospital in Zhengzhou is a good http://www.hnmt120.com/ for abortion?

The error is caused by: invalid literal for int () with base 10: 'abc'

5. Catch all exceptions

If you can't determine what type of exception to handle, but just want to return a readable exception error reminder if an exception occurs in the try statement, you can do this:

Try:

Int ('abc')

X = 1 +'1'

F = open ('non-existent document .txt')

Print (f.read ())

F.close ()

Except:

Print ('error Trout')

After running, the result is:

It's a mistake, Thumt.

Note: however, this is generally not recommended because it hides all errors that the program did not expect and were not ready to deal with.

II. Try-finally statement

If it is determined that there is a file named 'nonexistent document .txt', the open () function normally returns the file object, but the exception occurs on the x = 1 +'1' statement after successfully opening the file. At this point, Python will skip directly to the except statement, that is, the file is opened, but the command to close the file is skipped, causing the file not to be closed.

Try:

F = open ('non-existent document .txt')

Print (f.read ())

X = 1 +'1'

F.close ()

Except:

Print ('error Trout')

As a result, in order to implement the "wrap-up work that is not performed even if an exception occurs (such as saving the user document before the program crashes), finally is introduced to extend try:"

Try:

F = open ('non-existent document .txt')

Print (f.read ())

X = 1 +'1'

Except:

Print ('error Trout')

Finally:

F.close ()

Note: if there is no exception in the try statement block, the except statement block is skipped to execute the contents of the finally statement block. If an exception occurs, the contents of the except statement block are executed first and then the contents of the finally statement block. In short, the content in the finally statement block is what ensures that it will be executed anyway.

3. Try-except extension (silent when an exception occurs)

If we want to do nothing when an exception occurs and do nothing, we can use the pass statement to do so.

Try:

F = open ('non-existent document .txt')

Print (f.read ())

Except:

Pass

After running, the result is:

Process finished with exit code 0

IV. Else sentence collocation

Else statements can also be matched with exception handling in much the same way as circular statements: as long as there are no exceptions in the try statement block, the contents of the else statement block are executed.

Try:

Int (4.5)

Except ValueError as reason:

Print ('error T:' + str (reason))

Else:

Print ('nothing unusual!')

After running, the result is:

Nothing unusual!

Process finished with exit code 0

5. Concise with sentences

You may have seen the with statement when playing with the file, but do you all understand why you take it with you?

You may find it a bit troublesome to open and close files, and to pay attention to exception handling, so Python provides a with statement that abstracts try/except/finally-related details that are frequently used in file operations. Using with statements for file operations will greatly reduce the amount of code, and you no longer have to worry about the problem that the file was opened and forgot to close (with automatically helps close the file).

For example:

Try:

F = open ('non-existent document .txt','w')

Print (f.read ())

Except OSError as reason:

Print ('error T:' + str (reason))

Finally:

F.close ()

Using the with statement, you can change it to the following:

Try:

With open ('non-existent document .txt','w') as f:

Print (f.read ())

Except OSError as reason:

Print ('error T:' + str (reason))

Do you think it is very convenient? with the with statement, you don't have to worry about forgetting to close the file.

At this point, I believe you have a deeper understanding of "analyzing Python exception handling". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report