在其功能之外拾取异常

我有一个基于文本的程序,它在“while True:”样式循环中使用菜单和子菜单。您可以通过顶部菜单进入子菜单 - 已编辑以包含代码。


输出如下所示:


1 Collect Attachments

2 View Senders

3 Edit Senders

4 Quit


Choose an option: 1

Chose Collect Attachments


Enter a date dd-mm-yyyy: 21-01-2020

Enter how many days previous to search through: 7

Your search starts from 2020-01-21 00:00:00 and ends on 2020-01-14


0 Search Any

1 Hazel Blue

2 Duo Security

3 Esker Australia Pty Ltd

4 iiNet Billing Team

5 TeamViewer Sales

6 ple.com.au Gnangara Warehouse Team

7 info@thereceptionist.com.au

8 Amazon Web Services

There are 9 options.


Choose a sender (blank to exit):

You did not enter a valid number (ValueError)

问题是 ValueError 不应该出现在子菜单中。这都是自学的,所以我想我不明白异常处理是如何完成的。


红颜莎娜
浏览 143回答 2
2回答

千万里不及你

这是问题:>>> int("")Traceback (most recent call last):&nbsp; File "<stdin>", line 1, in <module>ValueError: invalid literal for int() with base 10: ''因此,当您在子菜单中说“空白退出”时,您应该:在转换为数字之前检查空字符串只使用字符串顺便说一句,学习logging包并logging.exception在抑制异常时使用通常很有用。此外,try您使用的涵盖数十行代码的大型子句通常不受欢迎,因为它很容易捕获意外异常,然后您已经注意到很难调试它。您通常应该尽可能地限制您的try条款,当然您的里程可能会有所不同。

四季花海

如果在 topMenu 中生成任何异常,您可以尝试此操作,那么它将不会进入子菜单,否则它将进入子菜单并执行操作。def main():&nbsp; &nbsp; &nbsp;def topMenu():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; while True:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # code if generate exception&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; subMenu()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # you can fetch specific exception or general&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; except Exception as e:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print(e)&nbsp; &nbsp; &nbsp; &nbsp; def subMenu():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("in submenu")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # code here...&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; topMenu()&nbsp;main()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python