尝试和Python除外

时间:2018-03-01 12:45:56

标签: python function exception error-handling try-catch

我做了这个例子,但它没有运行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

2 个答案:

答案 0 :(得分:1)

一些问题:

  1. 请修改缩进。缩进级别不匹配。
  2. 无需接受参数numCats,因为它已更改为用户提供的任何内容。
  3. 你没有调用函数my_fun(),这意味着永远不会有任何输出,因为函数只在被调用时运行。
  4. 这应该有效:

    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无。
  • 您的错误可能更具描述性,并且包含不恰当的输入本身。