C
C
codecity2010-09-08 20:36:27
.NET
codecity, 2010-09-08 20:36:27

.Net Invalid function argument format: ArgumentException or FormatException?

First, I will give the official description of exceptions according to MSDN. I will give in Russian, so that everyone can understand:
1. ArgumentException
This exception is thrown if one of the arguments passed to the method is invalid.
2. FormatException The
exception that is thrown if the format of the argument does not match the specifications of the parameter of the called method.
As can be seen from the official documentation, both exceptions should only occur due to an incorrect value of the argument passed to the method. Because FormatException does not inherit from ArgumentException - many people believe that there is a mistake in the official documentation (for 10 years no one has bothered to fix it).
What is a clear criterion for when which of these two exceptions to throw? Here, for example,

FileInfo fileInfo = new FileInfo("*"); // ArgumentException

and
Uri uri = new Uri("*"); // UriFormatException

or even
WebRequest.Create("*"); // UriFormatException

What are the common standards for throwing ArgumentException|FormatException so that there is no confusion?

Thank you for your attention!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
VenomBlood, 2010-09-09
@VenomBlood

In my opinion, format exceptions occur in strings or when explicitly passing an object that can have several presentation “formats” (although in this case it is better to implement a converter if possible and not throw exceptions at all).
If we passed the wrong data at all - ArgumentException, if we passed the correct data, but in the wrong format - FormatException. Only here it is necessary to determine already in the context of a specific application whether the input data can be incorrect at all (having one representation format) or all data is correct, but an error may occur due to different formats. For example, when generating a date from a string for a string like "dfdfdsfsf", I would throw an invalid format exception, and for the data "09/32/2010" - an invalid argument error (it will be generated correspondingly already at a lower level, when checking the date).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question