search
HomeBackend DevelopmentPython TutorialAbout exceptions in Python (Exception)
About exceptions in Python (Exception)Apr 24, 2018 pm 04:14 PM
exceptionpythonabout

The content of this article is about exceptions in Python, which has a certain reference value. Now I share it with you. Friends in need can refer to it.

Exceptions refer to exceptions in the program. , violation conditions. The exception mechanism refers to the program's handling method after an error occurs in the program. When an error occurs, the execution flow of the program changes and the control of the program is transferred to exception handling. The following article mainly summarizes relevant information about exceptions in Python. Friends in need can refer to it.

Preface

Exception class is a commonly used exception class, which includes StandardError, StopIteration, GeneratorExit, Warning and other exception classes. Exceptions in python are created using inheritance structures. Base class exceptions can be captured in the exception handler, or various subclass exceptions can be captured. Exceptions are captured using the try...except statement in python, and the exception clause is defined after the try clause. .

Exception handling in Python

The statement structure of exception handling

try:
 <statements>  #运行try语句块,并试图捕获异常
except <name1>:
 <statements>  #如果name1异常发现,那么执行该语句块。
except (name2, name3):
 <statements>  #如果元组内的任意异常发生,那么捕获它
except <name4> as <variable>:
 <statements>  #如果name4异常发生,那么进入该语句块,并把异常实例命名为variable
except:
 <statements>  #发生了以上所有列出的异常之外的异常
else:
<statements>   #如果没有异常发生,那么执行该语句块
finally:
 <statement>   #无论是否有异常发生,均会执行该语句块。

Explanation

  • ##else and finally are optional, there may be 0 or more except, but if an else occurs, there must be at least one except.


  • #No matter how you specify the exception, the exception is always identified by the instance object and most of the time is activated at any given moment. Once an exception is caught by an except clause somewhere in the program, it is dead unless it is reraised by another raise statement or an error.

raise statement

The raise statement is used to manually throw an exception. There are several calling formats:

  • raise #The instance can be created before the raise statement or in the raise statement.

  • #raise #Python will implicitly create an instance of the class

  • raise name(value) #Provide additional information while throwing an exception value

  • #raise # Rethrow the latest exception

  • raise exception from E


For example:


Throw a

ValueError with additional information: raise ValueError('we can only accept positive values')

When using from, the second expression specifies another exception class or instance, which will be attached to the

__cause__ attribute that raised the exception. If the exception raised is not caught, Python will print the exception as part of the standard error message:

For example, the following code:

try:
 1/0
except Exception as E:
 raise TypeError(&#39;bad input&#39;) from E

The execution result is as follows:

Traceback (most recent call last):
 File "hh.py", line 2, in <module>
 1/0
ZeropisionError: pision by zero

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
 File "hh.py", line 4, in <module>
 raise TypeError(&#39;bad input&#39;) from E
TypeError: bad input

assert statement

assert is mainly used to make assertions , usually used more in unit testing, will be introduced later.

with...as statement

The with statement supports a richer object-based protocol and can define support for entry and exit actions for code blocks.


The requirements for the environment management protocol corresponding to the with statement are as follows:

  • The environment manager must have

    __enter__ and __exit__method.

  • ##          
__enter__

The method will be run during initialization. If there is an ass, the return value of the __enter__ function will be assigned to The variables in the as clause, otherwise, are discarded directly.
The code nested in the code block will be executed.


If the with code block raises an exception, the

__exit__(type,value,traceback)

method will be called (with exception details). These are also the same values ​​returned by sys.exc_info. If this method returns false, the exception is re-raised. Otherwise, it terminates abnormally. Under normal circumstances, exceptions should be re-raised so that they can be passed outside the with statement.
If the with code block does not throw an exception, the

__exit__

method will still be called, and its type, value and traceback parameters will be passed as None.
The following is a simple custom context management class.

class Block:
 def __enter__(self):
  print(&#39;entering to the block&#39;)
  return self
 
 def prt(self, args):
  print(&#39;this is the block we do %s&#39; % args)

 def __exit__(self,exc_type, exc_value, exc_tb):
  if exc_type is None:
   print(&#39;exit normally without exception&#39;)
  else:
   print(&#39;found exception: %s, and detailed info is %s&#39; % (exc_type, exc_value))
  return False

with Block() as b:
 b.prt(&#39;actual work!&#39;)
 raise ValueError(&#39;wrong&#39;)

If you log out to the raise statement above, it will exit normally.


Without canceling the raise statement, the running result is as follows:

entering to the block
this is the block we do actual work!
found exception: <class &#39;ValueError&#39;>, and detailed info is wrong
Traceback (most recent call last):
 File "hh.py", line 18, in <module>
 raise ValueError(&#39;wrong&#39;)
ValueError: wrong

Exception handler


If an exception occurs, a tuple containing 3 elements can be returned by calling the

sys.exc_info()

function. The first element is the class that raised the exception, and the second is the instance that was actually raised. The third element, the traceback object, represents the stack of calls when the exception originally occurred. If everything is normal, 3 None will be returned.

Exception defined in Python’s Builtins module


|Exception Name|Description|
|BaseException|Root class for all exceptions|
| SystemExit|Request termination of Python interpreter|
|KeyboardInterrupt|User interrupted execution (usually by pressing Ctrl+C)|
|Exception|Root class for regular exceptions|
| StopIteration|Iteration has no further values|
| GeneratorExit|Exception sent to generator to tell it to quit|
| SystemExit|Request termination of Python interpreter|
| StandardError|Base class for all standard built-in exceptions|
|  ArithmeticError|Base class for all numeric calculation errors|
|   FloatingPointError|Error in floating point calculation|
|   OverflowError|Calculation exceeded maximum limit for numerical type|
|   ZeropisionError|pision (or modulus) by zero error (all numeric types)|
|  AssertionError|Failure of assert statement|
|  AttributeError|No such object attribute|
|  EOFError|End-of-file marker reached without input from built-in|
|  EnvironmentError|Base class for operating system environment errors|
|   IOError|Failure of input/output operation|
|   OSError|Operating system error|
|    WindowsError|MS Windows system call failure|
|    ImportError|Failure to import module or object|
|    KeyboardInterrupt|User interrupted execution (usually by pressing Ctrl+C)|
|   LookupError|Base class for invalid data lookup errors|
|    IndexError|No such index in sequence|
|    KeyError|No such key in mapping|
|   MemoryError|Out-of-memory error (non-fatal to Python interpreter)|
|   NameError|Undeclared/uninitialized object(non-attribute)|
|    UnboundLocalError|Access of an uninitialized local variable|
|   ReferenceError|Weak reference tried to access a garbage collected object|
|   RuntimeError|Generic default error during execution|
|    NotImplementedError|Unimplemented method|
|   SyntaxError|Error in Python syntax|
|    IndentationError|Improper indentation|
|     TabErrorg|Improper mixture of TABs and spaces|
|   SystemError|Generic interpreter system error|
|   TypeError|Invalid operation for type|
|   ValueError|Invalid argument given|
|    UnicodeError|Unicode-related error|
|     UnicodeDecodeError|Unicode error during decoding|
|     UnicodeEncodeError|Unicode error during encoding|
|     UnicodeTranslate Error|Unicode error during translation|
|  Warning|Root class for all warnings|
|   DeprecationWarning|Warning about deprecated features|
|   FutureWarning|Warning about constructs that will change semantically in the future|
|   OverflowWarning|Old warning for auto-long upgrade|
|   PendingDeprecation Warning|Warning about features that will be deprecated in the future|
|   RuntimeWarning|Warning about dubious runtime behavior|
|   SyntaxWarning|Warning about dubious syntax|
|   UserWarning|Warning generated by user code|

Related recommendations:


Detailed picture and text explanation of python exception handling method

The above is the detailed content of About exceptions in Python (Exception). For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Java中的ConcurrentModificationException异常的产生原因和解决方法Java中的ConcurrentModificationException异常的产生原因和解决方法Jun 25, 2023 am 10:33 AM

在Java中,当多个线程同时操作一个集合对象时,有可能会发生ConcurrentModificationException异常,该异常通常发生在遍历集合时进行修改或者删除元素的操作,这会导致集合的状态出现不一致,从而抛出异常。本文将深入探讨该异常的产生原因和解决方法。一、异常产生原因通常情况下,ConcurrentModificationException异

详细讲解Python之Seaborn(数据可视化)详细讲解Python之Seaborn(数据可视化)Apr 21, 2022 pm 06:08 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

详细了解Python进程池与进程锁详细了解Python进程池与进程锁May 10, 2022 pm 06:11 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

归纳总结Python标准库归纳总结Python标准库May 03, 2022 am 09:00 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于标准库总结的相关问题,下面一起来看一下,希望对大家有帮助。

分享10款高效的VSCode插件,总有一款能够惊艳到你!!分享10款高效的VSCode插件,总有一款能够惊艳到你!!Mar 09, 2021 am 10:15 AM

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

Python数据类型详解之字符串、数字Python数据类型详解之字符串、数字Apr 27, 2022 pm 07:27 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

详细介绍python的numpy模块详细介绍python的numpy模块May 19, 2022 am 11:43 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

一起来分析Python怎么操作XML文件一起来分析Python怎么操作XML文件May 05, 2022 pm 06:55 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了Python怎么操作XML文件的相关问题,包括了XML基础概述,Python解析XML文件、写入XML文件、更新XML文件等内容,下面一起来看一下,希望对大家有帮助。

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment