重新提出异常并不像预期的那样有效

Mos*_*she 0 python

我有这个相当复杂的try except块:

try:
  self.sorting = sys.argv[1]
  try:
    test_sorting_var = int(self.sorting)
    if test_sorting_var < 1:
      print "Sorting column number not valid."
      raise ValueError
    else:
      self.sorting = test_sorting_var
  except ValueError:
    print "There's a problem with the sorting value provided"
    print "Either the column doesn't exists or the column number is invalid"
    print "Please try a different sorting value or omit it."
    sys.exit(1)
  except:
    if self.sorting not in self.output_table.column_headers:
      print "Sorting column name not valid."
      raise ValueError
except:
  pass
Run Code Online (Sandbox Code Playgroud)

基本上我正在检查:

  1. 如果有的话 sys.argv[1]
  2. 如果是这样,请尝试它int,看看它是否小于1
  3. 如果int失败,请将其测试为字符串

在2 + 3中,如果测试没有成功,我会提出一个ValueError应该在except ValueError块中捕获并且它按预期执行:

Sorting column number not valid.
There's a problem with the sorting value provided
Either the column doesn't exists or the column number is invalid
Please try a different sorting value or omit it.
Run Code Online (Sandbox Code Playgroud)

但!该sys.exit(1)不会被调用,程序只是继续.

如何修复它甚至使其更具可读性?

L3v*_*han 5

在最后两行中,您可以捕获任何异常:

except:
  pass
Run Code Online (Sandbox Code Playgroud)

这包括由例外SystemExit引起的例外sys.exit.

为了解决这个问题,只捕获异常从派生Exception,SystemExit:

except Exception:
  pass
Run Code Online (Sandbox Code Playgroud)

一般来说,(几乎)从来都不是一个好主意,除了,总是捕获Exception,或者如果可能的话,更具体的东西.