未捕获异常

时间:2019-05-26 07:57:39

标签: python

我正在使用Jupyter Notebook和Python 3。 尝试捕获错误(TypeError)和打印消息,但是尽管出现了该错误,却没有捕获。

我尝试了类似的功能,但是没有参数,并且捕获了错误。

pandas数据帧在前面的代码中定义为df,具有6列,因此,如果我尝试仅添加5列,则应该引发TypeError

捕获错误的代码:

def example_working():
    try:
        newrowloc = len(df)
        df.loc[newrowloc] = [0, 0, 0, 0, 0]
        return df
    except Exception as e:
        print('Error occurred:')
        print(e)
    print('Operation finished')

输出:

example_working()
Error occurred:
cannot set a row with mismatched columns
Operation finished

未捕获错误的代码:

def addnewrow(x1, x2, x3, x4, x5, y):
    try:
        newrowloc = len(df)
        df.loc[newrowloc] = [x1, x2, x3, x4, x5, y]
        return df
    except Exception as e:
        print("Error occurred")
        print(e)
    print("Operation finished")

输出:

addnewrow(5,5,5,5,5)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-66-a741abd6cadc> in <module>
----> 1 addnewrow(5,5,5,5,5,)

TypeError: addnewrow() missing 1 required positional argument: 'y'

我希望try: except Exception as e:捕获到TypeError,但是由于某种原因却没有。

2 个答案:

答案 0 :(得分:-1)

您需要在<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="css/bootstrap.min.css"> <script src="js/bootstrap.min.js"></script> </head> <body> <div class="jumbotron text-center"> <h1>My First Bootstrap Page</h1> <p>Resize this responsive page to see the effect!</p> </div> <ul class="nav"> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item"> <a class="nav-link disabled" href="#">Disabled</a> </li> </ul> </body> </html>中调用函数,因为它的错误在于函数参数misach的数量。

try and except

要处理* args,

try: addnewrow(5,5,5,5,5) except Exception as e: print("Error occurred") print(e) print("Operation finished")

并处理相同的功能。

答案 1 :(得分:-1)

使用* args似乎可以按我的意愿工作:

def addnewrow(*args):
    try:
        newrowloc = len(df)
        df.loc[newrowloc] = [*args]
        return df
    except Exception as e:
        print("Error occurred")
        print(e)
    print("Operation finished")
addnewrow(5,5,5,5,5)
Error occurred
cannot set a row with mismatched columns
Operation finished