鱼C论坛

 找回密码
 立即注册
查看: 1290|回复: 1

[已解决]python自定义异常抛出

[复制链接]
发表于 2018-4-3 14:35:06 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
def GetSumAndAvg(num = 10):
    sum = 0
    i = num
    while i:
        try :
            a = input("please input a integer: ")
            if isinstance(a,int) == False:
                raise NonIntegerError
        except NonIntegerError:
            print('Input number is not a integer!')
        else:
            sum += a
            i -= 1
    print('sum is %d , average is %d' %(sum,sum/num))
想实现检查输入的数是否是整数,不是整数就抛出异常           
这里自定义了一个 异常,运行的时候程序报错  说未定义,请问raise不能这样定义自己命名的异常吗?         
            
>>> GetSumAndAvg(5)
please input a integer: 3.3
Traceback (most recent call last):
  File "C:/python/MyProject/exercise7_2_1.py", line 8, in GetSumAndAvg
    raise NonIntegerError
NameError: name 'NonIntegerError' is not defined

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<pyshell#25>", line 1, in <module>
    GetSumAndAvg(5)
  File "C:/python/MyProject/exercise7_2_1.py", line 9, in GetSumAndAvg
    except NonIntegerError:
NameError: name 'NonIntegerError' is not defined
最佳答案
2018-4-3 14:47:29
需要写成这样:
  1. def GetSumAndAvg(num = 10):
  2.     sum = 0
  3.     i = num
  4.     while i:
  5.         try :
  6.             a = input("please input a integer: ")
  7.             if isinstance(a,int) == False:
  8.                 raise Exception('NonIntegerError')
  9.         except Exception:
  10.             print('Input number is not a integer!')
  11.         else:
  12.             sum += a
  13.             i -= 1
  14.     print('sum is %d , average is %d' %(sum,sum/num))
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2018-4-3 14:47:29 | 显示全部楼层    本楼为最佳答案   
需要写成这样:
  1. def GetSumAndAvg(num = 10):
  2.     sum = 0
  3.     i = num
  4.     while i:
  5.         try :
  6.             a = input("please input a integer: ")
  7.             if isinstance(a,int) == False:
  8.                 raise Exception('NonIntegerError')
  9.         except Exception:
  10.             print('Input number is not a integer!')
  11.         else:
  12.             sum += a
  13.             i -= 1
  14.     print('sum is %d , average is %d' %(sum,sum/num))
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-3-10 04:11

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表