ValidationError or TypeError, ValueError - Exceptions

14,488

Solution 1

Python exceptions can be caught in this way:

try:
<your code>
except <Exception>:
    <CODE 2>

OR LIKE THIS

try:
    <your code>
except(<exception1>,<exception2>):
    <Code to handle exception>

You are simply handling multiple exceptions together. You can always split them. They are not 2 different ways. In your case the as is for logging it .

Here are a few examples:

try:
    <code>
except TypeError:
    <Code for handling exception>
except ValueError:
    <Code for handling exception>
except ValidationError:
    <Code for handling exception>
except:
    <Code for handling exception>

In the last case it catches exception of any type since no type is specified.
In Python programs can raise any exception for anything.
In fact exception is just a special class, even you can create one for your library.

So the best way to find about the exception is to read the docs of the library not the exception class.

If your program catches the exception and wants more detail about it for creating a log file the code can be written like this.

except TypeError as e:
    i=str(e)

In this case you are catching the exception and converting its detail to a string.
This is from the Django docs about the error which you are talking about.

Form validation happens when the data is cleaned. If you want to customize this process, there are various places to make changes, each one serving a different purpose. Three types of cleaning methods are run during form processing. These are normally executed when you call the is_valid() method on a form. There are other things that can also trigger cleaning and validation (accessing the errors attribute or calling full_clean() directly), but normally they won’t be needed.

In general, any cleaning method can raise ValidationError if there is a problem with the data it is processing, passing the relevant information to the ValidationError constructor. See below for the best practice in raising ValidationError. If no ValidationError is raised, the method should return the cleaned (normalized) data as a Python object.

Some further references:

The link to docs
This link has info about other common builtin exception classes.

Solution 2

They are different blocks of code for handling different exceptions.

However in this example, both cases have the same logic for how they handle each exception.

It might make more sense if we split up the cases into 3 different blocks of code:

except TypeError as error:
    LOGGER.error('Type error: ', exc_info=True);
except ValueError as error:
    LOGGER.error('Value error: ', exc_info=True);
except ValidationError error:
    LOGGER.error('Validation error: ', exc_info=True);

TypeError will be thrown when an incorrect type is used

ValueError will be thrown when an incorrect value is used

ValidationError will be thrown when the validation fails

The program will handle each exception differently

Share:
14,488

Related videos on Youtube

may
Author by

may

Updated on June 04, 2022

Comments

  • may
    may almost 2 years

    I am quite a newbie understanding of how to catch exceptions in python. I have a question regarding those two types of ways of catching exceptions. I only found useful information about ValidationError regarding here

    But I did not quite understand if it can be used besides django or what are the error messages that I can expect about it. I saw this code sample regarding the validation of types.

    except (TypeError, ValueError) as error:
                LOGGER.error('Error e.g.', exc_info=True)
    
    except ValidationError:
                LOGGER.error('Error e.g', exc_info=True)
    

    So for TypeError and ValueError for me, it is clear:

    exception ValueError

    Raised when an 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.

    exception TypeError

    Raised when an operation or function is applied to an object of inappropriate type. The associated value is a string giving details about the type mismatch.

    In conclusion, I am trying to understanding what would be the advantage of the second code with ValidationError, but it could be tricky as I did not find good documentation about. If someone could share knowledge about ValidationError, I would highly appreciate,

    I am raising this question because I am going to use related library and I have not seen the exceptions being treated like this.

    https://pypi.org/project/related/

    Thank you community!

    • BoarGules
      BoarGules about 5 years
      Something that may be unclear to you: TypeError and ValueError are built into Python. But a library can and often will define its own exceptions. ValidationError comes from a library you are using.
    • Anonymous
      Anonymous about 5 years
      For searching about exceptions you should look about the docs of your library not the exception since it itself will have no docs
    • may
      may about 5 years
      @Anonymous yes, I raised the question because I am getting to know a new library called related, in order to do a validation pypi.org/project/related
    • Anonymous
      Anonymous about 5 years
      @may OK then you can just see the file for exceptions in it and find the statement
    • Anonymous
      Anonymous about 5 years
      raise validation error
  • may
    may about 5 years
    But I guess this ValidationError is not supported for all the validation process as I am using this new lib called related, and this type exception is not listed there, as an example.