Home Backend Development Python Tutorial Python standard exception development experience summary

Python standard exception development experience summary

Mar 28, 2017 pm 04:28 PM
python

在我们编写脚本或者进行软件开发过程中总会遇见很多的异常和错误,而python里面有两个非常重要的功能,能够很好的处理异常和任何意外错误,这两个功能就是异常处理和断言。

异常处理:主要包含语法错误和其他的标准异常,标准异常介绍如下表。

    断言:断言是一种理智检查,当程序的测试完成,你可以打开或关闭。断言的最简单的方法就是把它比作 raise-if 语句 (或者更准确,加 raise-if-not 声明). 一个表达式进行测试,如果结果出现 false,将引发异常。断言是由 assert 语句,在Python中新的关键字,在Python1.5版本中引入使用的关键字。

程序员常常放置断言来检查输入的有效,或在一个函数调用后检查有效的输出。

一、标准异常表

Python standard exception development experience summary

异常示例:

1、FileNotFoundError
尝试打开文d:\\openstack.txt文件由于文件不存在就会报出FIleNotFoundError:
f=open("d:\\openstack.txt")
Traceback (most recent call last):
  File "<pyshell>", line 1, in <module>
    f=open("d:\\openstack.txt")
FileNotFoundError: [Errno 2] No such file or directory: 'd:\\openstack.txt'
 
2、ZeroDivisionError
除法运算或取模运算中,除数为零的情况
 >>> 5/0
Traceback (most recent call last):
  File "<pyshell>", line 1, in <module>
    5/0
ZeroDivisionError: division by zero
3、ImportError
一般是在导入模块时,由于模块不存在等原因导致报错
>>> import  wwww
Traceback (most recent call last):
  File "<pyshell>", line 1, in <module>
    import  wwww
ImportError: No module named 'wwww'
4、ValueError
 一般是由于传入参数的数据类型错误引起报错。
 >>> a="sterc"
>>> int(a)
Traceback (most recent call last):
  File "<pyshell>", line 1, in <module>
    int(a)
ValueError: invalid literal for int() with base 10: 'sterc'
>>></module></pyshell></module></pyshell></module></pyshell></module></pyshell>
Copy after login

二、异常处理

  python中包含两种异常处理语句,可以使用try...except...finally或者try...except..else语句来处理异常,接下来简单的介绍两种语句的语法以及两者的区别:

try语句原理:

首先,执行try子句(在关键字try和关键字except之间的语句)

如果没有异常发生,忽略except子句,try子句执行后结束。

如果在执行try子句的过程中发生了异常,那么try子句余下的部分将被忽略。如果异常的类型和 except 之后的名称相符,那么对应的except子句将被执行。最后执行 try 语句之后的代码。

如果一个异常没有与任何的except匹配,那么这个异常将会传递给上层的try中。

一个 try 语句可能包含多个except子句,分别来处理不同的特定的异常。最多只有一个分支会被执行。

处理程序将只针对对应的try子句中的异常进行处理,而不是其他的 try 的处理程序中的异常。

一个except子句可以同时处理多个异常,这些异常将被放在一个括号里成为一个元组。

try...except..else语法:

try:
   You do your operations here
   ......................
except ExceptionI:
   If there is ExceptionI, then execute this block.
except ExceptionII:
   If there is ExceptionII, then execute this block.
   ......................
else:
   If there is no exception then execute this block. 
    
单个 try 语句可以有多个except语句。 当 try 块包含可能抛出不同类型的异常声明这是有用的
也可以提供一个通用的 except 子句来处理异常(不提倡)
except子句后,可以包括 else 子句。 如果代码在try:块不引发异常则代码在 else 块执行
else是可以正常运行部存在异常的代码,这不需要 try: 块的保护
  try:
   fh = open("testfile", "w+")
   fh.write("This is my test file for exception handling!!")
except IOError:
   print ("Error: can\'t find file or read data")
else:
   print ("Written content in the file successfully")
   fh.close()
   
  正常执行后就会生成testfile文件里面的内容为:This is my test file for exception handling!
  而控制台输出结果如下:
  Written content in the file successfully
Copy after login

用except子句处理多个异常

刚才我们的示例是处理了一个类型的异常,而except可以处理多个类型的异常例如

except(ValueError,ImportError,RuntimeError)这是可以将多个类型的标准错误写成一个元组,但是做个类型容易造成我们队类型的报错分析难度大。

try:
   fh = open("testfile", "r")
   fh.write("This is my test file for exception handling!!")
except (ValueError,ImportError,RuntimeError):
   print ("Error: can\'t find file or read data")
else:
   print ("Written content in the file successfully")
   fh.close()
  结果:
  Error: can't find file or read data  #这里没有报出是那个类型的标准错误。
Copy after login

try-finally子句:

    使用 try: 块. finally 块是必须执行,而不管 try 块是否引发异常或没有。try-finally 语句的语法是这样的。

try:
   You do your operations here;
   ......................
   Due to any exception, this may be skipped.
Copy after login
except ExceptionI:
   If there is ExceptionI, then execute this block.
except ExceptionII:
   If there is ExceptionII, then execute this block.
Copy after login

finally:

   This would always be executed.
Copy after login

 try...except...finally无论try块能否正常的执行,finally是一定会执行的模块。

try:
   fh = open("testfile", "r")
   fh.write("This is my test file for exception handling!!")
except (ValueError,ImportError,RuntimeError):
   print ("Error: can\'t find file or read data")
finally:
   print ("Written content in the file successfully")
   fh.close() #关闭文件
  结果:文件中没有写入内容,
  控制台输出以下内容:
Error: can't find file or read data
Written content in the file successfully
Copy after login

引发异常

可以通过使用 raise 语句触发几个方面的异常。对于 raise 语句的一般语法如下。

语法

raise [Exception [, args [, traceback]]]

这里,Exception 是异常的类型(例如,NameError)argument 为异常的参数值。该参数是可选的;如果没有提供,异常的参数是None。

最后一个参数 traceback,也可选的(实践中很少使用),并且如果存在的话,是用于异常的回溯对象。

示例

异常可以是一个字符串,一个类或一个对象。大多数Python的异常核心是触发类异常,使用类的一个实例参数的异常。定义新的异常是很容易的,可以按如下做法  -

def functionName( level ):
    if level <p style="text-align: left;">注意:为了捕捉异常,一个“except”语句必须是指出抛出类对象异常或简单的字符串异常。例如,捕获异常上面,我们必须编写 except 子句如下 -</p><pre class="brush:php;toolbar:false">try:
   Business Logic here...
except Exception as e:
   Exception handling here using e.args...
else:
   Rest of the code here...
Copy after login

下面的例子说明如何使用触发异常:

#!/usr/bin/python3
def functionName( level ):
    if level <p style="text-align: left;">这将产生以下结果</p><p style="text-align: left;">error in level argument -10</p><p style="text-align: left;">用户定义的异常</p><p style="text-align: left;">Python中,还可以通过内置的异常标准的派生类来创建自己的异常。</p><p style="text-align: left;">这里是关于 RuntimeError 的一个例子。这里一个类被创建,它是 RuntimeError 的子类。当需要时,一个异常可以捕获用来显示更具体的信息,这非常有用。</p><p style="text-align: left;">在try块,用户定义的异常将引发,并夹在 except 块中。 变量e是用来创建网络错误 Networkerror 类的实例。</p><pre class="brush:php;toolbar:false">class Networkerror(RuntimeError):
   def __init__(self, arg):
      self.args = arg
Copy after login

所以上面的类定义后,可以引发异常如下 -

try:
   raise Networkerror("Bad hostname")
except Networkerror,e:
   print e.args
Copy after login

The above is the detailed content of Python standard exception development experience summary. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Can vscode be used for mac Can vscode be used for mac Apr 15, 2025 pm 07:36 PM

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

Can vscode run ipynb Can vscode run ipynb Apr 15, 2025 pm 07:30 PM

The key to running Jupyter Notebook in VS Code is to ensure that the Python environment is properly configured, understand that the code execution order is consistent with the cell order, and be aware of large files or external libraries that may affect performance. The code completion and debugging functions provided by VS Code can greatly improve coding efficiency and reduce errors.

Golang vs. Python: Concurrency and Multithreading Golang vs. Python: Concurrency and Multithreading Apr 17, 2025 am 12:20 AM

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

See all articles