Python: difference between ValueError and Exception?

54,964

Solution 1

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.

Solution 2

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.

Solution 3

To add extra detail onto the above answers, you can chain the except statements in the try clause. So you might first check for ValueError, or another type, then lastly you can check for Exception (anything that wasn't already caught by ValueError).

As mentioned above, ValueError inherits from Exception, so it is a more specific type of Exception. docs: https://docs.python.org/3/library/exceptions.html

Example:

Assuming mycheck() function passes back some exception text, we can access it with the below variable 'e'.

try:
    value = mycheck(value)
except ValueError as e:
    print(f"'{value}' did not pass mycheck ValueCheck: {e}")
except Exception as e:
    print(f"'{value}' did not pass mycheck validation: {e}")

You asked about the difference of raising ValueError versus raising Exception. Both behave similarly. It's a matter of how specific you want to be. It would be recommended generally to raise the most specific type of error in order to provide the most useful error feedback to the user.

If you look at how error trapping can be chained in my example, then you might see how your choice of which type of error to raise would affect the output to the user.

Share:
54,964
vlad.rad
Author by

vlad.rad

Areas: Data Engineering, ETL Actively using: pandas, numpy (Python), Tableau, AWS Interests: Algorithms, architectures in automotive, chatbots

Updated on July 29, 2021

Comments

  • vlad.rad
    vlad.rad over 2 years

    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 the same - I got an error message.

    I have made a research on this question on SO, but found no discussion on this. Then I read the documentation of exceptions, and found the following definition of ValueError:

    Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.

    So as I understand, an Exception is a more general term, and ValueError can be applied in some specific cases. But since the results of raising both things are the same, I want to understand, what is the practical meaning of differentiating between a ValueError and an Exception. Python version should be here not relevant. Thank you!

    EDIT: Thanks to your answers I got it, what is the difference between both terms in try-exception construct. But how do they differ in case of just raising them, not excepting?

    raise Exception('blah') 
    

    and

    raise ValueError('blah') 
    

    Answering to @PeterWood: in both cases I just got the error message "blah", but in one case it was "Exception: blah", and in the second: "ValueError: blah". And I see in this case no practical difference between them both.