5. Please Define your own exception class MyException(Show message: HAVE ERRORs) and throw this exception object in your method(6 points)
时间: 2024-02-24 12:00:07 浏览: 67
Sure! Here's an example implementation of the MyException class and how to throw it within a method:
```python
class MyException(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)
def my_method(param):
if param < 0:
raise MyException("Input parameter must be non-negative")
# rest of method code here
# example usage
try:
my_method(-1)
except MyException as e:
print("Caught exception:", e.message)
```
In this example, the `MyException` class extends the built-in `Exception` class and defines a custom error message. The `my_method` function checks if the input parameter is non-negative, and if it's not, it raises a `MyException` object with the custom error message. The `try`/`except` block then catches the exception and prints the error message.
阅读全文