编写两个自己定义的异常类,然后在编写一个类,在其中编写两个方法f1()和f2()。在f2() 中抛出自己定义的第一个常类对象,在f1() 中调用f2(),并捕捉其中的异常,然后在catch字句中抛出第二个异常。
时间: 2023-06-14 10:07:48 浏览: 58
自定义异常类步骤
自定义异常类1:
```python
class CustomException1(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return f'Custom Exception 1: {self.msg}'
```
自定义异常类2:
```python
class CustomException2(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return f'Custom Exception 2: {self.msg}'
```
编写的类:
```python
class MyClass:
def f1(self):
try:
self.f2()
except CustomException1 as e:
print(f'Exception caught in f1: {e}')
raise CustomException2('Exception in f1') from e
def f2(self):
raise CustomException1('Exception in f2')
```
使用:
```python
mc = MyClass()
try:
mc.f1()
except CustomException2 as e:
print(f'Exception caught in main: {e}')
```
输出:
```
Exception caught in f1: Custom Exception 1: Exception in f2
Exception caught in main: Custom Exception 2: Exception in f1
```
阅读全文