About catching ANY exception

后端 未结 8 1063
一整个雨季
一整个雨季 2020-11-22 07:23

How can I write a try/except block that catches all exceptions?

相关标签:
8条回答
  • 2020-11-22 08:06

    There are multiple ways to do this in particular with Python 3.0 and above

    Approach 1

    This is simple approach but not recommended because you would not know exactly which line of code is actually throwing the exception:

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

    Approach 2

    This approach is recommended because it provides more detail about each exception. It includes:

    • Line number for your code
    • File name
    • The actual error in more verbose way

    The only drawback is tracback needs to be imported.

    import traceback
    
    def bad_method():
        try:
            sqrt = 0**-1
        except Exception:
            print(traceback.print_exc())
    
    bad_method()
    
    0 讨论(0)
  • 2020-11-22 08:09

    You can but you probably shouldn't:

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

    However, this will also catch exceptions like KeyboardInterrupt and you usually don't want that, do you? Unless you re-raise the exception right away - see the following example 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
    
    0 讨论(0)
提交回复
热议问题