当前位置:网站首页>Chapter 9 Exceptions try...except...else...finally
Chapter 9 Exceptions try...except...else...finally
2022-07-31 07:40:00 【MallocLu】
异常
Python使用异常对象来表示异常状态,并在遇到错误时引发异常.异常对象未被处理(或捕获)时,The program will terminate with an error message(traceback).
>>> 1 / 0
Traceback (most recent call last):
File "<input>", line 1, in <module>
ZeroDivisionError: division by zero
Exceptions include built-in exceptions and custom exceptions2种(没有本质区别,Built-in exceptions iePythonExceptions that are already defined and used frequently,Custom exceptions are mostly related to the actual business development)
内置异常
Common built-in exceptions only,其实还有很多
BaseException
+-- Exception
| +-- AttributeError 引用属性或给它赋值失败时引发
| +-- OSError Raised when the operating system cannot perform the specified task
| +-- IndexError Raised when an index does not exist in the used sequence
| +-- KeyError Raised when using a key that does not exist in the map
| +-- NameError 找不到名称(变量)时引发
| +-- SyntaxError 代码不正确时引发
| +-- TypeError Raised when a built-in operation or function is used with a variable of the wrong type
| +-- ValueError 将内置操作或函数用于这样的对象时引发:其类型正确但包含的值不合适
| +-- ZeroDivisionError 在除法或求模运算的第二个参数为零时引发
+-- KeyboardInterrupt
+-- SystemExit
自定义异常
class NewException(Exception):
def __init__(self, errorInfo):
super().__init__()
self.errorInfo = errorInfo
def __str__(self):
return self.errorInfo
抛出异常
1) raise:单独一个 raise.该语句引发当前上下文中捕获的异常(比如在 except 块中),或默认引发 RuntimeError 异常
注意:raise ... from None的用法
# 引发默认的RuntuimeError
raise
# Traceback (most recent call last):
# File "C:/Users/shang/Desktop/pythonProject/main.py", line 1, in <module>
# raise
# RuntimeError: No active exception to reraise
# 1 / 0 The location is triggeredZeroDivisionError,raiseThrows the entire exception stack
try:
1 / 0
except ZeroDivisionError:
raise
# Traceback (most recent call last):
# File "C:/Users/shang/Desktop/pythonProject/main.py", line 2, in <module>
# 1 / 0
# ZeroDivisionError: division by zero
# 1 / 0 The location is triggeredZeroDivisionError,except ZeroDivisionErrorException handling was thrownValueError,except Exception通过raiseThrows the entire exception stack
try:
try:
1 / 0
except ZeroDivisionError:
raise ValueError
except Exception:
raise
# Traceback (most recent call last):
# File "C:/Users/shang/Desktop/pythonProject/main.py", line 3, in <module>
# 1 / 0
# ZeroDivisionError: division by zero
#
# During handling of the above exception, another exception occurred:
#
# Traceback (most recent call last):
# File "C:/Users/shang/Desktop/pythonProject/main.py", line 5, in <module>
# raise ValueError
# ValueError
# 通过raise ... from None来禁用上下文,raiseThe entire exception stack is not thrown but fromValueErrorBegin the outgoing exception stack
try:
try:
1 / 0
except ZeroDivisionError:
raise ValueError from None
except Exception:
raise
# Traceback (most recent call last):
# File "C:/Users/shang/Desktop/pythonProject/main.py", line 5, in <module>
# raise ValueError from None
# ValueError
2) raise ZeroDivisionError
# Traceback (most recent call last):
# File "E:\anaconda\envs\py37tfcpu\lib\code.py", line 90, in runcode
# exec(code, self.locals)
# File "<input>", line 1, in <module>
# ZeroDivisionError
3) raise ZeroDivisionError("除数不能为0")
# Traceback (most recent call last):
# File "E:\anaconda\envs\py37tfcpu\lib\code.py", line 90, in runcode
# exec(code, self.locals)
# File "<input>", line 1, in <module>
# ZeroDivisionError: 除数不能为0
捕获异常
总体结构
# tryblock required,except块&finallyChoose one of two blocks,else块可选
# try块中的代码出现异常,终止tryThe execution of the code following the block is transferred inexcept块
# tryThe code in the block does not throw an exception,执行完tryTransfer in after the blockelse块
# tryThe code in the block regardless of whether an exception occurs,最后执行finally块
try:
pass
except:
pass
else:
pass
finally:
pass
except块
# 捕获所有异常,不建议使用,因为包含KeyboardInterrupt等
except:
# Catch an exception
except ZeroDivisionError:
print("The second number can't bu zero!")
# 捕获多种异常
except ZeroDivisionError:
print("The second number can't bu zero!")
except TypeError:
print("That wasn't a number, was it?")
# 捕获多种异常
except (ZeroDivisionError, TypeError):
print('Your numbers were bogus ...')
# Access the exception object itself
except (ZeroDivisionError, TypeError) as e:
print(e)
处理异常
1)不处理,程序将异常终止
1 / 0
print('Hello World')
# Traceback (most recent call last):
# File "C:/Users/shang/Desktop/pythonProject/main.py", line 1, in <module>
# 1 / 0
# ZeroDivisionError: division by zero
#
# Process finished with exit code 1
2)忽略,The program continues to execute the following statement
try:
1 / 0
except Exception as e:
pass
print('Hello World')
# Hello World
#
# Process finished with exit code 0
3)处理,执行完exceptAfter the processing of the block,The program continues to execute the following statement
try:
1 / 0
except Exception as e:
print(e)
print('Hello World')
# division by zero
# Hello World
#
# Process finished with exit code 0
4)抛出,Handed over to the outer caller to handle
try:
1 / 0
except Exception as e:
raise
print('Hello World')
警告
#使用warnings模块中的warn函数warn发出警告
>>>from warnings import warn
>>>warn("I've got a bad feeling about this.")
#警告只显示一次,如果再次运行最后一行代码,什么事情都不会发生
#使用warnings模块中的filterwarningsThe function suppresses warnings(或特定类型的警告),and specify the measures to be taken,如"error"(警告)或"ignore"(忽略警告)
>>>from warnings import filterwarnings
>>>filterwarnings("ignore")
>>>warn("Anyone out there?")
>>>filterwarnings("error")
>>>warn("Something is very wrong!")
Traceback (most recent call last):
File "<input>", line 1, in <module>
UserWarning: Something is very wrong!
#发出警告时,You can specify the warning category to raise(必须是Warning的子类,默认UserWarning).
>>>filterwarnings("error")
>>>warn("This function is really old...", DeprecationWarning)
Traceback (most recent call last):
File "<input>", line 1, in <module>
DeprecationWarning: This function is really old...
#Filter specific types of warnings based on exceptions
>>>filterwarnings("ignore", category=DeprecationWarning)
>>>warn("Another deprecation warning.", DeprecationWarning)
>>>warn("Something else.")
Traceback (most recent call last):
File "<input>", line 1, in <module>
UserWarning: Something else.
边栏推荐
- 基于LSTM的诗词生成
- The Perfect Guide|How to use ODBC for Agentless Oracle Database Monitoring?
- 多进程全局变量失效、变量共享问题
- LeetCode:952. 按公因数计算最大组件大小【欧拉筛 + 并查集】
- 服务器和客户端信息的获取
- 测试 思维导图
- 2022.07.24_每日一题
- 在 ASP.NET Core 应用程序启动时运行代码的 3 种方法
- Install the gstreamer development dependency library to the project sysroot directory
- 【面试:并发篇38:多线程:线程池】ThreadPoolExecutor类的基本概念
猜你喜欢
随机推荐
Kubernetes scheduling
nohup principle
2022.07.12_Daily Question
2022.07.18_每日一题
【Go报错】go go.mod file not found in current directory or any parent directory 错误解决
Postgresql source code learning (33) - transaction log ⑨ - see the overall process of log writing from the insert record
04-SDRAM: Read Operation (Burst)
金融租赁业务
2022.07.13_每日一题
【并发编程】ReentrantLock的lock()方法源码分析
毫米波技术基础
'vite' is not an internal or external command, nor is it a runnable program or batch file.
gstreamer's caps event and new_segment event
SQL Server Datetime2数据类型
单点登录 思维导图
LeetCode brush # 376 # Medium - swing sequence
【科普向】5G核心网架构和关键技术
2022.07.18 _ a day
‘vite‘ 不是内部或外部命令,也不是可运行的程序 或批处理文件。
小实战项目之——吃货联盟订餐系统









