Python: difference between ValueError and Exception?

前端 未结 2 490
忘了有多久
忘了有多久 2021-01-02 00:45

I am trying to understand what is a difference between raising a ValueError and an Exception. I have tried both in the same code (even in the same branch) and the result was

相关标签:
2条回答
  • 2021-01-02 01:14

    You said it, ValueError is a specific Exception. A short example :

    try:
        print int("hello world")
    except ValueError:
        print "A short description for ValueError"
    

    If you change "hello world" with an int, print int(42), you will not raise the exception.

    You can see doc about exceptions here.

    0 讨论(0)
  • 2021-01-02 01:26

    ValueError inherits from Exception. You can decide to trap either only ValueError, or Exception, that's what exception inheritance is for.

    In this example:

    try:
        a=12+"xxx"
    except Exception:
        # exception is trapped (TypeError)
    

    exception is trapped, all exceptions (except BaseException exceptions) are trapped by the except statement.

    In this other example:

    try:
        a=12+"xxx"
    except ValueError:
        # not trapped
    

    Here, exception is NOT trapped (TypeError is not ValueError and does not inherit)

    You generally use specific exceptions to trap only the ones that are likely to occur (best example is IOError when handling files), and leave the rest untrapped. The danger of catching all exceptions is to get a piece of code that does not crash, but does nothing.

    (editing the answer in response to your edit:) when you raise an exception: you're creating an instance of Exception which will be filtered out by future except ValueError: statements. the message is different because the representation of the exception (when printed) includes the exception class name.

    0 讨论(0)
提交回复
热议问题