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
- 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
ValueError with additional information: raise ValueError('we can only accept positive values')
__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:
try: 1/0 except Exception as E: raise TypeError('bad input') 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('bad input') from E TypeError: bad input
assert statement
with...as statement
- The environment manager must have
__enter__
and
__exit__method.
##
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
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
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('entering to the block') return self def prt(self, args): print('this is the block we do %s' % args) def __exit__(self,exc_type, exc_value, exc_tb): if exc_type is None: print('exit normally without exception') else: print('found exception: %s, and detailed info is %s' % (exc_type, exc_value)) return False with Block() as b: b.prt('actual work!') raise ValueError('wrong')
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 'ValueError'>, and detailed info is wrong Traceback (most recent call last): File "hh.py", line 18, in <module> raise ValueError('wrong') ValueError: wrongException handler
If an exception occurs, a tuple containing 3 elements can be returned by calling the
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 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:
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!

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

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

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

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

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

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

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

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
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 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
Powerful PHP integrated development environment
