@@ -277,23 +277,49 @@ an integer or string that the other module will accept::
277277 3221225985
278278
279279
280- Exceptions raised by :mod: ` ipaddress `
281- =====================================
280+ Getting more detail when instance creation fails
281+ ================================================
282282
283283When creating address/network/interface objects using the version-agnostic
284- factory functions, any errors will be reported as :exc: `ValueError `.
284+ factory functions, any errors will be reported as :exc: `ValueError ` with
285+ a generic error message that simply says the passed in value was not
286+ recognised as an object of that type. The lack of a specific error is
287+ because it's necessary to know whether the value is *supposed * to be IPv4
288+ or IPv6 in order to provide more detail on why it has been rejected.
289+
290+ To support use cases where it is useful to have access to this additional
291+ detail, the individual class constructors actually raise the
292+ :exc: `ValueError ` subclasses :exc: `ipaddress.AddressValueError ` and
293+ :exc: `ipaddress.NetmaskValueError ` to indicate exactly which part of
294+ the definition failed to parse correctly.
295+
296+ The error messages are significantly more detailed when using the
297+ class constructors directly. For example::
298+
299+ >>> ipaddress.ip_address("192.168.0.256")
300+ Traceback (most recent call last):
301+ ...
302+ ValueError: '192.168.0.256' does not appear to be an IPv4 or IPv6 address
303+ >>> ipaddress.IPv4Address("192.168.0.256")
304+ Traceback (most recent call last):
305+ ...
306+ ipaddress.AddressValueError: Octet 256 (> 255) not permitted in '192.168.0.256'
285307
286- For some use cases, it desirable to know whether it is the address or the
287- netmask which is incorrect. To support these use cases, the class
288- constructors actually raise the :exc: `ValueError ` subclasses
289- :exc: `ipaddress.AddressValueError ` and :exc: `ipaddress.NetmaskValueError `
290- to indicate exactly which part of the definition failed to parse correctly.
308+ >>> ipaddress.ip_network("192.168.0.1/64")
309+ Traceback (most recent call last):
310+ ...
311+ ValueError: '192.168.0.1/64' does not appear to be an IPv4 or IPv6 network
312+ >>> ipaddress.IPv4Network("192.168.0.1/64")
313+ Traceback (most recent call last):
314+ ...
315+ ipaddress.NetmaskValueError: '64' is not a valid netmask
291316
292- Both of the module specific exceptions have :exc: `ValueError ` as their
317+ However, both of the module specific exceptions have :exc: `ValueError ` as their
293318parent class, so if you're not concerned with the particular type of error,
294319you can still write code like the following::
295320
296321 try:
297- ipaddress.IPv4Address (address)
322+ network = ipaddress.IPv4Network (address)
298323 except ValueError:
299- print('address/netmask is invalid:', address)
324+ print('address/netmask is invalid for IPv4:', address)
325+
0 commit comments