关于捕获任何异常

时间:2011-02-14 09:46:58

标签: python exception-handling

如何编写捕获所有异常的try / except块?

8 个答案:

答案 0 :(得分:675)

除了裸except:条款(正如其他人所说的那样你不应该使用),你可以简单地抓住Exception

import traceback
import logging

try:
    whatever()
except Exception as e:
    logging.error(traceback.format_exc())
    # Logs the error appropriately. 

您通常只会考虑在代码的最外层执行此操作,例如,您希望在终止之前处理任何其他未捕获的异常。

except Exception优于except的优势在于,有一些例外情况无法捕捉,最明显是KeyboardInterruptSystemExit:如果你抓住并吞下那些你可能会让任何人都难以退出你的剧本。

答案 1 :(得分:467)

你可以,但你可能不应该:

try:
    do_something()
except:
    print "Caught it!"

但是,这也会捕获像KeyboardInterrupt这样的例外情况,你通常不希望这样,是吗?除非您立即重新提出异常 - 请参阅以下示例from the docs

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except IOError as (errno, strerror):
    print "I/O error({0}): {1}".format(errno, strerror)
except ValueError:
    print "Could not convert data to an integer."
except:
    print "Unexpected error:", sys.exc_info()[0]
    raise

答案 2 :(得分:89)

您可以执行此操作来处理常规异常

try:
    a = 2/0
except Exception as e:
    print e.__doc__
    print e.message

答案 3 :(得分:48)

非常简单的例子,类似于这里发现的例子:

http://docs.python.org/tutorial/errors.html#defining-clean-up-actions

如果您尝试捕获所有异常,则将所有代码放在“try:”语句中,代替“print”执行可能引发异常的操作。“'。

try:
    print "Performing an action which may throw an exception."
except Exception, error:
    print "An exception was thrown!"
    print str(error)
else:
    print "Everything looks great!"
finally:
    print "Finally is called directly after executing the try statement whether an exception is thrown or not."

在上面的示例中,您将按以下顺序查看输出:

1)执行可能引发异常的动作。

2)最后在执行try语句后直接调用是否抛出异常。

3)“抛出异常!”或者“一切看起来都很棒!”取决于是否抛出异常。

希望这有帮助!

答案 4 :(得分:46)

要捕获所有可能的异常,请抓住try: something() except BaseException as error: print('An exception occurred: {}'.format(error)) 。它位于异常层次结构之上:

Python 3: https://docs.python.org/3.5/library/exceptions.html#exception-hierarchy

Python 2.7: https://docs.python.org/2.7/library/exceptions.html#exception-hierarchy

public class ProjectData
{
        public static string Username {get;set;}
}

public class ViewModel {
   public string UserName {
      get{ return ProjectData.Username ; }
      set { ProjectData.Username  = value; }
   }
}

但正如其他人提到的那样,除非你有充分的理由,否则你通常不会这样做。

答案 5 :(得分:14)

我刚刚发现了这个小技巧,用于测试Python 2.7中的异常名称。有时我在代码中处理了特定的异常,所以我需要一个测试来查看该名称是否在处理的异常列表中。

try:
    raise IndexError #as test error
except Exception as e:
    excepName = type(e).__name__ # returns the name of the exception

答案 6 :(得分:7)

有多种方法可以做到这一点,特别是在Python 3.0及更高版本中

方法1

这是一种简单的方法,但不建议使用,因为您不知道确切的代码行实际引发了异常:

def bad_method():
    try:
        sqrt = 0**-1
    except Exception as e:
        print(e)

bad_method()

方法2

推荐这种方法,因为它提供了有关每个异常的更多详细信息。它包括:

  • 您的代码的行号
  • 文件名
  • 以更详细的方式显示实际错误

唯一的缺点是需要导入tracback。

import traceback

def bad_method():
    try:
        sqrt = 0**-1
    except Exception:
        print(traceback.print_exc())

bad_method()

答案 7 :(得分:4)

try:
    whatever()
except:
    # this will catch any exception or error

值得一提的是,这不是正确的Python编码。这也会捕获您可能不想捕获的许多错误。

相关问题