如果未发生错误则引发异常

时间:2019-06-17 07:32:02

标签: python python-3.x selenium exit try-except

我正在python3中使用Selenium Webdriver。当驱动程序到达某个页面并且如果存在带有类shiftUp的某个类元素时,我想在该点打印响应并停止执行。目前,我正在执行以下操作:

flag = 0
try:
    error_source_file = driver.find_element_by_class_name("shiftUp")
    flag = 1
except:
    pass
if flag:
    print("RESPONSE")
    sys.exit()

我想要一种正确的方法。

2 个答案:

答案 0 :(得分:1)

使用else子句:

try:
    error_source_file = driver.find_element_by_class_name("shiftUp")
except NoSuchElementException:
    pass
else:
    print("RESPONSE")
    sys.exit()

在未引发错误的情况下触发:https://docs.python.org/3/tutorial/errors.html#handling-exceptions

  

try … except语句具有可选的 else子句,当存在该子句时,该子句必须遵循除条款之外的所有子句。对于try子句未引发异常的必须执行的代码,这很有用。

  

使用else子句比向try子句添加其他代码更好,因为它避免了意外捕获{{1}保护的代码未引发的异常}。

出于类似的原因,我建议只捕获try … except:您不想捕获不想要的错误。

答案 1 :(得分:-1)

为什么不呢?

    Dim RectTemplate As New Rectangle(0, 0, 250, 250)
    Dim GapPx As Int32 = 12                  ' set gap between rectangles
    Dim StaPt As New Point(GapPx, GapPx * 2)   ' set starting point
    Dim N As Int32 = Val(TextBox1.Text)                  ' set (or get) the totalnumber of rectangles
    Dim nL As Int32 = Math.Floor((e.PageBounds.Width - GapPx) / (RectTemplate.Width + GapPx))  ' number of rectangles per row
    Dim nR As Int32 = Math.Ceiling(N / nL)   ' number of rows of rectangles 
    For ir = 0 To nR - 1       ' process all rows
        For il = 0 To nL - 1   ' process all rectangles in a row
            If (nR * RectTemplate.Height) > e.PageBounds.Height Then
                e.HasMorePages = False
            Else
                Dim rect As New Rectangle(StaPt.X + il * (RectTemplate.Width + GapPx), StaPt.Y + ir * (RectTemplate.Height + GapPx), RectTemplate.Width, RectTemplate.Height)
                e.Graphics.DrawRectangle(Pens.Sienna, rect)
            End If
        Next
    Next

如果try: error_source_file = driver.find_element_by_class_name("shiftUp") print("RESPONSE") sys.exit() except NoSuchElementException: pass 方法引发异常,则不会执行error_source_file之后的行。

  

注意:请考虑确定要捕获的异常的类型(例如:find_element),否则您可以忽略错误,这确实很糟糕。

相关问题