1. 一般异常处理方式(报错)
try:
command
except Exception as e:
pass
print(e)
上述为标准语法,在执行try里面的代码的时候如果报错会将错误赋给e对象。
2. 异常分类:
Exception:能捕捉到所有异常
IOErro: IO错误
IndexError: 捕捉索引错误
ValueError: 值出错
等等等…
可以分类处理异常:
try:
pass
except ValueError as e:
pass
except IndexError as e:
pass
except Exception as e:
pass
else:
pass
finally:
pass
- 异常处理,只要遇到一个后续的except就不再执行
- 如果不抛出异常则执行else
- 不管抛不抛异常,都会执行finally
3. 主动触发异常
try:
raise Exception('发生异常...')
except Exception as e:
print(e)
4. 自定义异常类
class MyErro(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
try:
raise MyErro('wrong')
except Exception as e:
print(e)
5. 断言asser
assert 条件
执行代码遇到这一句,
- 如果条件为真,不影响程序执行
- 如果条件为假,则会抛出AssertionError
一般用于强制用户服从某些条件
本文详细介绍了Python中异常处理的基本语法,包括try-except语句的使用,异常的分类如IOError、IndexError和ValueError等,以及如何主动触发异常和自定义异常类。此外,还讲解了断言assert的用法,帮助读者掌握全面的异常处理技巧。
1520

被折叠的 条评论
为什么被折叠?



