Python中如何使用raise关键字引发assert异常?

2026-05-24 13:341阅读0评论SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计145个文字,预计阅读时间需要1分钟。

Python中如何使用raise关键字引发assert异常?

pythonclass MyException(Exception): def __init__(self, error_msg): self.error_msg=error_msg

def __str__(self): return self.error_msg

try: print('手动触发exception') raise MyException('出错了')

Python中如何使用raise关键字引发assert异常?

class MyException(Exception):
def __init__(self,error_msg):
self.error_msg=error_msg
def __str__(self):
return self.error_msg
try:
print('手动触发exception')
raise MyException('出错了')#手动触发了exception错误 会被except Exception捕获
except Exception as e:
print('error:',e)

PS D:\python\py_test> python3 .\t1.py

手动触发exception
error: 出错了

print(123)

assert 1==1##若成立则执行后面的代码 反之直接报错

print(456)


本文共计145个文字,预计阅读时间需要1分钟。

Python中如何使用raise关键字引发assert异常?

pythonclass MyException(Exception): def __init__(self, error_msg): self.error_msg=error_msg

def __str__(self): return self.error_msg

try: print('手动触发exception') raise MyException('出错了')

Python中如何使用raise关键字引发assert异常?

class MyException(Exception):
def __init__(self,error_msg):
self.error_msg=error_msg
def __str__(self):
return self.error_msg
try:
print('手动触发exception')
raise MyException('出错了')#手动触发了exception错误 会被except Exception捕获
except Exception as e:
print('error:',e)

PS D:\python\py_test> python3 .\t1.py

手动触发exception
error: 出错了

print(123)

assert 1==1##若成立则执行后面的代码 反之直接报错

print(456)