class IllegalArgLenException(Exception): def __init__(self, message): self.message = message class NotNumberException(Exception): def __init__(self, message): self.message = message class NotTriangleException(Exception): def __init__(self, message): self.message = message def is_triangle(a, b, c): if a + b > c and a + c > b and b + c > a: return True else: return False try: nums = input("请输入三个数字,以逗号分隔:").split(",") if len(nums) != 3: raise IllegalArgLenException("参数个数不正确") a, b, c = float(nums[0]), float(nums[1]), float(nums[2]) if not (isinstance(a, (int, float)) and isinstance(b, (int, float)) and isinstance(c, (int, float))): raise NotNumberException("输入不是数字类型") if not is_triangle(a, b, c): raise NotTriangleException("a, b, c不能构成三角形") print("三角形三边长分别为:{:.2f}, {:.2f}, {:.2f}".format(a, b, c)) print("三角形周长为:{:.2f}".format(a + b + c)) except IllegalArgLenException as e: print(e.message) except NotNumberException as e: print(e.message) except NotTriangleException as e: print(e.message) except Exception as e: print("发生未知异常:", e) finally: print("程序运行结束")解释一下这段代码
时间: 2023-12-06 08:43:25 浏览: 28
这段代码实现了一个判断三个数字能否构成三角形的程序,主要涉及到以下几个类和函数:
1. `IllegalArgLenException`:当输入参数个数不正确时,抛出该异常。
2. `NotNumberException`:当输入值不是数字类型时,抛出该异常。
3. `NotTriangleException`:当三个数字不能构成三角形时,抛出该异常。
4. `is_triangle(a, b, c)`:判断三个数字能否构成三角形。
在 `try` 块中,首先通过 `input` 函数获取用户输入的三个数字,并使用 `split` 函数将其以逗号分隔成一个列表。接着,使用 `len` 函数判断列表的长度是否为 3,如果不为 3,则抛出 `IllegalArgLenException` 异常。然后,使用 `float` 函数将列表中的每个元素转换为浮点数类型,并判断是否为数字类型,如果不是数字类型,则抛出 `NotNumberException` 异常。最后,调用 `is_triangle(a, b, c)` 函数判断三个数字能否构成三角形,如果不能构成三角形,则抛出 `NotTriangleException` 异常。如果以上步骤都没有出现异常,则输出三角形三边长和周长。
在 `except` 块中,分别捕获不同类型的异常,并输出对应异常的提示信息。在 `finally` 块中,输出程序运行结束的提示信息。
相关问题
编写程序,计算圆的面积,若半径为负值则抛出异常(圆的面积公式: )。 class NumericalError(Exception): def __init__(self): self.message = '请输入正确的数据' class CircleArea: def circle(self): try: radius = int(input("请输入圆的半径:\n")) if radius <0: raise NumericalError() except as e: print(e.message) else: # 计算圆的面积 print(3.14*radius**2) circle_area = circle_area.circle()
好的,我来为你编写这个程序。下面是完整的代码:
```python
class NumericalError(Exception):
def __init__(self):
self.message = '请输入正确的数据'
class CircleArea:
def circle(self):
try:
radius = int(input("请输入圆的半径:\n"))
if radius < 0:
raise NumericalError()
except NumericalError as e:
print(e.message)
except ValueError:
print('请输入数字')
else:
# 计算圆的面积
print('圆的面积为:', 3.14 * radius ** 2)
circle_area = CircleArea()
circle_area.circle()
```
在这个程序中,我们定义了一个 `NumericalError` 异常类,用于在半径为负数时抛出异常。在 `CircleArea` 类中,我们通过 `try-except-else` 语句来处理异常和计算圆的面积。
具体来说,在 `try` 块中,我们使用 `input` 函数获取用户输入的半径,并将其转换为整数类型。如果用户输入的是负数,我们使用 `raise` 语句抛出 `NumericalError` 异常。如果用户输入的不是数字,那么 `int` 函数会抛出 `ValueError` 异常,我们也需要在 `except` 块中进行处理。
如果没有抛出异常,那么程序会进入 `else` 块,计算圆的面积并打印出来。
你可以将上述代码粘贴到你的 Python 环境中执行,测试一下程序的运行结果。
class DefinitionException(Exception): def __init__(self, message): super().__init__(message) n = 9999 try: i = input("请输入数字:") result = n / int(i) print(result) print("{0}除以{1}等于{2}".format(n, i, result)) except ZeroDivisionError as e: raise DefinitionException("0不能做除数") except ValueError as e: raise DefinitionException("数字无效") # 虽然抛出了DefinitionException异常,但却没有进行捕获。 except DefinitionException as e: print("自定义异常", e)这串代码有什么问题吗?为什么我始终无法捕捉到异常?
这段代码的问题在于,虽然在代码中定义了`DefinitionException`异常类,并在代码中抛出了该异常,但在`try-except`语句中并没有捕获该异常。因此,当程序抛出`DefinitionException`异常时,程序会崩溃并且不会被捕获。
要解决这个问题,需要在`try-except`语句中增加一个`except`子句,用于捕获`DefinitionException`异常。例如:
```python
class DefinitionException(Exception):
def __init__(self, message):
super().__init__(message)
n = 9999
try:
i = input("请输入数字:")
result = n / int(i)
print(result)
print("{0}除以{1}等于{2}".format(n, i, result))
except ZeroDivisionError as e:
raise DefinitionException("0不能做除数")
except ValueError as e:
raise DefinitionException("数字无效")
except DefinitionException as e:
print("自定义异常", e)
```
在这个例子中,我们增加了一个`except`子句,用于捕获`DefinitionException`异常并进行处理。这样,当程序抛出`DefinitionException`异常时,程序会进入`except`子句中,并打印出异常信息。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)