我做了这个例子,但它没有运行try和Python中的处理错误。
using (PasswordGenerationEntities db = new PasswordGenerationEntities())
{
db.Database.Log = Console.Write;
tblPassword newObj = (from c in db.tblPasswords
where c.Username == obj.Username
select c).First();
if(newObj != null)
{
int num = r.Next();
string newOtp = num.ToString();
newObj.Otp = newOtp;
db.SaveChanges();
dbTime = DateTime.Now;
Session["Username"] = newObj.Username.ToString();
return RedirectToAction("ChangePassword");
}
}
我试过了:
def my_fun(numCats):
print('How many cats do you have?')
numCats = input()
try:
if int(numCats) >=4:
print('That is a lot of cats')
else:
print('That is not that many cats')
except ValueError:
print("Value error")
我做了其他例子,它能够捕获except Exception:
except (ZeroDivisionError,ValueError) as e:
except (ZeroDivisionError,ValueError) as error:
我正在使用Jupyter笔记本Python 3。
非常感谢您对此事的任何帮助。
我正在打电话
ZeroDivisionError
答案 0 :(得分:1)
一些问题:
numCats
,因为它已更改为用户提供的任何内容。my_fun()
,这意味着永远不会有任何输出,因为函数只在被调用时运行。这应该有效:
def my_fun():
print('How many cats do you have?\n')
numCats = input()
try:
if int(numCats) > 3:
print('That is a lot of cats.')
else:
print('That is not that many cats.')
except ValueError:
print("Value error")
my_fun() ## As the function is called, it will produce output now
答案 1 :(得分:1)
以下是您的代码的重写版本:
def my_fun():
numCats = input('How many cats do you have?\n')
try:
if int(numCats) >= 4:
return 'That is a lot of cats'
else:
return 'That is not that many cats'
except ValueError:
return 'Error: you entered a non-numeric value: {0}'.format(numCats)
my_fun()
<强>解释强>
input()
将输入之前显示的字符串作为参数。input()
提供输入,因此您的函数不需要参数。return
值,如有必要,之后再打印。{li>而不是让您的函数print
字符串和return
无。