编程技术网

关注微信公众号,定时推送前沿、专业、深度的编程技术资料。

 找回密码
 立即注册

QQ登录

只需一步,快速开始

极客时间

Python 3引发错误以进行异常处理:Python 3 throwing error for exception handling

tkaessmann Python 2022-5-11 10:55 8人围观

腾讯云服务器
Python 3引发错误以进行异常处理的处理方法

我上周开始学习python,但在这里我找不到错误的地方:

I started learning python last week and I'm unable to get what's wrong here:

def add(x,y): """Adds 2 numbers and returns the result""" return x+y def sub(x,y): """Subtracts 2 numbers and returns the result""" return x-y a = int(input("Enter first number")) b = int(input("Enter second number")) c = int(input("Enter 1 for subtraction , 2 for addition and 3 for both")) try: if c>3: raise ValueError() except ValueError(): print ("Wrong choice") else: print ("Your choice is ",c) if (c==1): print ("Subtraction of 2 numbers=",(sub(a,b))) if (c==2): print ("Addition of 2 numbers = ",(add(a,b))) if (c==3): print ("Subtraction of 2 numbers=",(sub(a,b))) print ("Addition of 2 numbers = ",(add(a,b))) 

如果我输入4,则会引发此错误:

If I enter 4 it throws this error:

Traceback (most recent call last): File "C:/Program Files (x86)/Python35-32/calculator.py", line 15, in <module> raise ValueError() ValueError 

在处理上述异常期间,发生了另一个异常:

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "C:/Program Files (x86)/Python35-32/calculator.py", line 16, in <module> except ValueError(): TypeError: catching classes that do not inherit from BaseException is not allowed 

问题解答

您正试图捕获 ValueError()实例,Python希望您在该实例上进行过滤类型.删除通话:

You are trying to catch an instance of ValueError(), where Python expects you to filter on the type. Remove the call:

except ValueError: print ("Wrong choice") 

这篇关于Python 3引发错误以进行异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程技术网(www.editcode.net)!

腾讯云服务器 阿里云服务器
关注微信
^