错误通常指的是程序中的语法错误和逻辑错误
# 缺少冒号,导致语法错误
if True
print("Hello,world!")
D:\PycharmProjects\pythonProject.venv\Scripts\python.exe D:\PycharmProjects\pythonProject\test.py
File “D:\PycharmProjects\pythonProject\test.py”, line 2122
if True
^
SyntaxError: expected ‘:’Process finished with exit code 1
# 除数为零
10 / 0 # ZeroDivisionError
D:\PycharmProjects\pythonProject.venv\Scripts\python.exe D:\PycharmProjects\pythonProject\test.py
Traceback (most recent call last):
File “D:\PycharmProjects\pythonProject\test.py”, line 2131, in
10 / 0 # ZeroDivisionError
~^
ZeroDivisionError: division by zeroProcess finished with exit code 1
try:
result = 1 / 0
except ZeroDivisionError:
print("除数不能为零")
try:
with open("nonexistent_file.txt","r") as file:
content = file.read()
except FileNotFoundError:
print("文件未找到")
my_list = [1,2,3]
try:
print(my_list[3])
except IndexError:
print("索引超出范围")
my_dict = {'name': 'Alice', 'age': 25}
# 尝试访问不存在的键
try:
value = my_dict['city']
except KeyError as e:
print(f"捕获到 KeyError: {e}")
# 字符串'abc'无法转换为整数
num_str = "abc"
try:
num = int(num_str)
except ValueError as e:
print(f"捕获到 ValueError: {e}")
# 字符串和整数是不同的数据类型,不能直接用 + 运算符进行相加操作
string_value = "Hello"
int_value = 123
try:
result = string_value + int_value
except TypeError as e:
print(f"捕获到 TypeError: {e}")
try:
num = int(input("请输入一个整数: "))
result = 10 / num
print(f"结果是: {result}")
except ValueError:
print("输入不是有效的整数。")
except ZeroDivisionError:
print("除数不能为零。")
try:
file = open("data.txt","r")
except FileNotFoundError:
print("文件不存在!")
else:
print(file.read())
finally:
file.close() #确保文件关闭
def validate_age(age):
if age < 0:
raise ValueError("年龄不能为负数!")
return age
try:
validate_age(-5)
except ValueError as e:
print(e) #输出:年龄不能为负数!
try:
# process_data()
except ValueError:
print("处理数据时出错")
raise #重新抛出异常供上层处理
class InvalidEmailError(Exception):
"""邮箱格式无效异常"""
def __init__(self,email):
self.email = email
super().__init__(f"邮箱 {email} 格式无效!")
def send_email(email):
if "@" not in email:
raise InvalidEmailError(email)
#发送邮件逻辑...
try:
send_email("user.exampe.com")
except InvalidEmailError as e:
print(e)
def add(a,b):
print(f"输入的参数 a = {a},b = {b}")
result = a + b
print(f"计算结果:{result}")
return result
add(4,4)
import pdb
def divide(a,b):
pdb.set_trace() #断点
return a / b
divide(10,0)
n(next):执行下一行
c(continue):继续执行到下一个断点
q(quit):退出调试
import unittest
def add(a,b):
return a + b
class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2,3),5)
self.assertRaises(TypeError,add,"2",3)
if __name__ == "__main__":
unittest.main()
# test_math.py
def test_add():
assert add(2,3) == 5
def test_add_fail():
with pytest.raises(TypeError):
add("2",3)
# 运行测试:终端执行 pytest_math.py
# 不推荐
try:
risky_operation()
except: # 捕获所有异常
pass
# 推荐
try:
risky_operation()
except (ValueError,IOError) as e:
handle_erroe(e)
with open("file.txt","r") as f:
content = f.read()
import logging
logging.basicConfig(filename="app.log",level=logging.ERROR)
try:
process()
except Exception as e:
logging.error("处理失败:%s",e,exc_info=True)
def safe_divide(a,b):
if b == 0:
return 0 # 或抛出特定异常
return a / b
data = [1,2,"3",4]
results = []
for item in data:
try:
results.append(int(item))
except ValueError:
print(f"无法转换:{item}")
BaseException
├── BaseExceptionGroup
├── GeneratorExit
├── KeyboardInterrupt
├── SystemExit
└── Exception
├── ArithmeticError
│ ├── FloatingPointError
│ ├── OverflowError
│ └── ZeroDivisionError
├── AssertionError
├── AttributeError
├── BufferError
├── EOFError
├── ExceptionGroup [BaseExceptionGroup]
├── ImportError
│ └── ModuleNotFoundError
├── LookupError
│ ├── IndexError
│ └── KeyError
├── MemoryError
├── NameError
│ └── UnboundLocalError
├── OSError
│ ├── BlockingIOError
│ ├── ChildProcessError
│ ├── ConnectionError
│ │ ├── BrokenPipeError
│ │ ├── ConnectionAbortedError
│ │ ├── ConnectionRefusedError
│ │ └── ConnectionResetError
│ ├── FileExistsError
│ ├── FileNotFoundError
│ ├── InterruptedError
│ ├── IsADirectoryError
│ ├── NotADirectoryError
│ ├── PermissionError
│ ├── ProcessLookupError
│ └── TimeoutError
├── ReferenceError
├── RuntimeError
│ ├── NotImplementedError
│ ├── PythonFinalizationError
│ └── RecursionError
├── StopAsyncIteration
├── StopIteration
├── SyntaxError
│ └── IndentationError
│ └── TabError
├── SystemError
├── TypeError
├── ValueError
│ └── UnicodeError
│ ├── UnicodeDecodeError
│ ├── UnicodeEncodeError
│ └── UnicodeTranslateError
└── Warning
├── BytesWarning
├── DeprecationWarning
├── EncodingWarning
├── FutureWarning
├── ImportWarning
├── PendingDeprecationWarning
├── ResourceWarning
├── RuntimeWarning
├── SyntaxWarning
├── UnicodeWarning
└── UserWarning