What are exceptions in python? How should exceptions be handled?

乌拉乌拉~
Release: 2018-08-16 17:36:55
Original
2121 people have browsed it

Today in this article we will learn about exception handling in python. First we need to understand python exceptions. Only by knowing all the exceptions in python and the reasons why they occur, We can deal with python error and exception handling methods to quickly handle exceptions.

What is an exception?

An exception is an event that occurs during program execution and affects the normal execution of the program.

Generally, an exception occurs when Python cannot handle the program normally.

Exception is a Python object that represents an error.

When an exception occurs in a Python script, we need to catch and handle it, otherwise the program will terminate execution.

Exception handling

To catch exceptions, you can use the try/except statement.

The try/except statement is used to detect errors in the try statement block, so that the except statement can capture the exception information and handle it.

If you don't want to end your program when an exception occurs, just catch it in try.

Grammar:

The following is the syntax of a simple try....except...else:

try:
<语句>        #运行别的代码
except <名字>:
<语句>        #如果在try部份引发了&#39;name&#39;异常
except <名字>,<数据>:
<语句>        #如果引发了&#39;name&#39;异常,获得附加的数据
else:
<语句>        #如果没有异常发生
Copy after login

The working principle of try is that after starting a try statement , python marks it in the context of the current program, so that you can return here when an exception occurs. The try clause is executed first, and what happens next depends on whether an exception occurs during execution.

If an exception occurs when the statement after try is executed, python will jump back to try and execute the first except clause matching the exception. After the exception is handled, the control flow will pass through the entire try statement (unless it is in A new exception is thrown when handling the exception).

If an exception occurs in the statement after try, but there is no matching except clause, the exception will be submitted to the upper try, or to the top level of the program (this will end the program and print the default error message).

If no exception occurs when the try clause is executed, python will execute the statement after the else statement (if there is an else), and then the control flow passes through the entire try statement.

Example

The following is a simple example, it opens a file, writes the content in the file, and it does not happen Exception:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
try:
    fh = open("testfile", "w")
    fh.write("这是一个测试文件,用于测试异常!!")
except IOError:
    print "Error: 没有找到文件或读取文件失败"
else:
    print "内容写入文件成功"
    fh.close()
Copy after login

Output result of the above program:

$ python test.py 
内容写入文件成功
$ cat testfile       # 查看写入的内容
这是一个测试文件,用于测试异常!!
Copy after login

In this article, we explain what exceptions are and how to handle them. If you don’t understand, you can give it a try. After all, hands-on practice is the best way to verify what you have learned. Finally, I hope this article can bring some help to you who are learning python.

For more related knowledge, please visit the Python tutorial column on the php Chinese website.

The above is the detailed content of What are exceptions in python? How should exceptions be handled?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!