Python exceptions All In One
Python exceptions All In One
Different exceptions are raised for different reasons.
Common exceptions:
ImportError
: an import fails;IndexError
: a list is indexed with an out-of-range number;NameError
: an unknown variable is used;SyntaxError
: the code can't be parsed properly;TypeError
: a function is called on a value of an inappropriate type;ValueError
: a function is called on a value of the correct type, but with an inappropriate value.
Python has several other built-in
exceptions, such as ZeroDivisionError
and OSError
.
Third-party libraries also often define their own exceptions.
single except
#!/usr/bin/env python3
# coding: utf8
__author__ = 'xgqfrms'
__editor__ = 'vscode'
__version__ = '1.0.1'
__github__ = 'https://github.com/xgqfrms/Python-3.x-All-In-One'
__git__ = 'https://github.com/xgqfrms/Python-3.x-All-In-One.git'
__copyright__ = """
Copyright (c) 2012-2050, xgqfrms; mailto:xgqfrms@xgqfrms.xyz
"""
"""
/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2020-01-01
* @updated 2023-06-01
*
* @description
* @augments
* @example
* @link
*
*/
try:
num1 = 7
num2 = 0
num3 = 2
print (num1 / num3)
print("✅ Done calculation")
print (num1 / num2)
except ZeroDivisionError:
print("❌ An error occurred, due to zero division")
"""
$ py3 ./exception-handling-try-except.py
3.5
✅ Done calculation
❌ An error occurred, due to zero division
"""
multi except
#!/usr/bin/env python3
# coding: utf8
__author__ = 'xgqfrms'
__editor__ = 'vscode'
__version__ = '1.0.1'
__github__ = 'https://github.com/xgqfrms/Python-3.x-All-In-One'
__git__ = 'https://github.com/xgqfrms/Python-3.x-All-In-One.git'
__copyright__ = """
Copyright (c) 2012-2050, xgqfrms; mailto:xgqfrms@xgqfrms.xyz
"""
"""
/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2020-01-01
* @updated 2023-06-01
*
* @description
* @augments
* @example
* @link
*
*/
try:
variable = 10
print(variable + "hello")
print(variable / 2)
except ZeroDivisionError:
print("❌ Divided by zero")
except (ValueError, TypeError):
print("❌ ValueError or TypeError occurred")
"""
$ py3 ./exception-handling-try-multi-except.py
❌ ValueError or TypeError occurred
"""
finally
try:
print("Hello World")
print(1 / 0)
except ZeroDivisionError:
print("❌ Divided by zero")
finally:
print("👻 This code will run no matter what")
"""
$ py3 ./exception-handling-try-except-finally.py
Hello World
❌ Divided by zero
👻 This code will run no matter what
"""
else
try:
print(1)
except ZeroDivisionError:
print("❌ ZeroDivisionError")
else:
print("✅")
try:
print(1/0)
except ZeroDivisionError:
print("❌❌ ZeroDivisionError")
else:
print("✅✅")
"""
$ py3 ./exception-handling-try-except-else.py
1
✅
❌❌ ZeroDivisionError
"""
raise
# You can throw (or `raise`) exceptions when some condition occurs.
# You need to specify the `type` of the exception raised.
try:
num = 102
if num > 100:
# 自定 throw error 类型
raise ValueError
except ValueError:
print("❌ ValueError")
# 没有处理 raise ❌
num = 102
if num > 100:
# 自定 throw error 类型
raise ValueError
"""
$ py3 ./exception-handling-raise.py
❌ ValueError
Traceback (most recent call last):
File "/Users/xgqfrms-mm/Documents/github/Python-3.x-All-In-One/src/./exception-handling-raise.py", line 16, in <module>
raise ValueError
ValueError
"""
python get exception message
Python 3
"""
You are making a program to post tweets. Each tweet must not exceed 42 characters.
Complete the program to raise an exception, in case the length of the tweet is more than 42 characters.
You can use the len() function to calculate the length of the string.
"""
tweet = input()
try:
#your code goes here
if(len(tweet) > 42):
raise ValueError("tweet 超出 42 字符的最大长度限制 ❌")
# raise SyntaxError("tweet 超出 42 字符的最大长度限制 ❌")
except Exception as err:
print("❌ Error =", err)
print("❌❌ Error args =", err.args)
print("❌❌❌ Error args[0] =", err.args[0])
# except Exception, err:
# print("❌ Error msg", err.msg)
# print("❌❌ Error message", err.message)
else:
print("✅ Posted")
"""
$ py3 ./exception-handling-say-something.py
###########################################
❌ Error = tweet 超出 42 字符的最大长度限制 ❌
❌❌ Error args = ('tweet 超出 42 字符的最大长度限制 ❌',)
❌❌❌ Error args[0] = tweet 超出 42 字符的最大长度限制 ❌
$ py3 ./exception-handling-say-something.py
xgqfrms
✅ Posted
"""
"""
class SyntaxError(Exception):
msg: str
lineno: int | None
offset: int | None
text: str | None
filename: str | None
if sys.version_info >= (3, 10):
end_lineno: int | None
end_offset: int | None
class SystemError(Exception): ...
class TypeError(Exception): ...
class ValueError(Exception): ...
class FloatingPointError(ArithmeticError): ...
class OverflowError(ArithmeticError): ...
class ZeroDivisionError(ArithmeticError): ...
class ModuleNotFoundError(ImportError): ...
class IndexError(LookupError): ...
class KeyError(LookupError): ...
class UnboundLocalError(NameError): ...
"""
Python 2
# old ❌
try:
# ...
except Exception, e:
# ...
# new ✅
try:
# ...
except Exception as e:
# ...
https://docs.python.org/zh-cn/3/library/exceptions.html
https://docs.python.org/3/tutorial/errors.html
⚠️ 注意事项:
对于 Python 3 的 Exception,与 Python 2 的 Exception 相比,有两个需要注意的地方:
- 在 Python 3 Exception 的 except 子句中,不支持使用逗号 ',' 分隔 Exception 和 e,所以需要采用
as
关键词进行替换; - 与 Python 2 Exception 类相比,Python 3 Exception 类没有
message
成员变量。
针对这个问题,可以使用err.args
方法获取得到相关的异常信息。
针对这个问题,可以使用sys.exc_info()
方法获取得到相关的异常信息。
https://www.cnblogs.com/xgqfrms/p/17589042.html#5197603
demos
#!/usr/bin/env python3
# coding: utf8
__author__ = 'xgqfrms'
__editor__ = 'vscode'
__version__ = '1.0.1'
__github__ = 'https://github.com/xgqfrms/Python-3.x-All-In-One'
__git__ = 'https://github.com/xgqfrms/Python-3.x-All-In-One.git'
__copyright__ = """
Copyright (c) 2012-2050, xgqfrms; mailto:xgqfrms@xgqfrms.xyz
"""
"""
/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2020-01-01
* @updated 2023-06-01
*
* @description
* @augments
* @example
* @link
*
*/
# setter/getter
class Pizza:
def __init__(self, toppings):
self.toppings = toppings
self._pineapple_allowed = False
@property
def pineapple_allowed(self):
return self._pineapple_allowed
# property setter
@pineapple_allowed.setter
def pineapple_allowed(self, value):
if value:
password = input("Enter the password: ")
if password == "123":
self._pineapple_allowed = value
else:
raise ValueError("Alert! Intruder!")
@pineapple_allowed.getter
def pineapple_allowed(self):
return "✅" + str(self._pineapple_allowed)
try:
pizza = Pizza(["cheese", "tomato"])
print(pizza.toppings)
print(pizza._pineapple_allowed)
print("\npizza.pineapple_allowed =", pizza.pineapple_allowed)
pizza.pineapple_allowed = True
print(pizza.pineapple_allowed)
except ValueError:
print("ValueError")
finally:
print("finished")
"""
$ py3 ./class-property-setter-getter.py
['cheese', 'tomato']
False
pizza.pineapple_allowed = ✅False
Enter the password: 123
✅True
"""
(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
refs
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/17589042.html
未经授权禁止转载,违者必究!