python raise Exception
时间: 2025-04-16 17:22:53 浏览: 22
### 如何在Python中抛出自定义异常
为了创建并抛出自定义异常,在 Python 中通常会继承 `Exception` 类来构建新的异常类。下面是一个简单的例子展示如何实现这一点:
```python
class CustomError(Exception):
"""Custom error class inheriting from base Exception."""
def __init__(self, message="This is a custom exception"):
self.message = message
super().__init__(self.message)
def test_custom_exception(value):
if value < 0:
raise CustomError("Negative values are not allowed") # Raising the custom exception with specific message.
try:
test_custom_exception(-1)
except CustomError as ce:
print(f"Caught an exception: {ce}") # Handling the caught exception by printing it out.
```
在这个实例里,当传递给函数 `test_custom_exception()` 的参数小于零时,就会触发名为 `CustomError` 的自定义异常,并附带一条特定的消息说明原因。
通过这种方式,开发者可以根据应用程序的需求设计更加具体化的错误处理机制,从而提高程序的健壮性和可维护性[^1]。
阅读全文
相关推荐


















