In the first place, the mechanism called "exception" was created to enable the description ** "What should I do when the process is skipped for this reason?" ** (I don't think I'm angry). .. The "exception" that is sent is exactly that "reason for this and that", and even if it is said that "the processing was blown away for some general reason", it can only be returned as "foolish". It's **.
not good. Of course I'm not saying it's totally useless, but ** I have something to do before that **.
** Decide "who, how far, what to do". ** ** For example, suppose there is an operation of "reading a file, parsing it, and holding it as an object". At this time (although it is a little detailed), four characters appear as characters: "the one who passes the location of a certain file", "the one who reads a certain file", "the one who parses what is read", and "the one who holds it".
What and how much should these guys do? Common sense suggests that "the one who passes the location of a file" is at least "what would be the location of the file", "(probably) in a string", and "without loss". There will be. Based on this assumption, "the one who reads a certain file" does not have to think about "does something like the location of this file really indicate the location of the file?" Even if you go to read and there is no file, you can complain (= exception), "Hey, I went to look for the information you gave me, didn't I ?!".
To put it coolly, it's called CoC, ** Design by contract **. What, "Isn't there an exception!"? What are you talking about ** I'm saying that the exception is for use when the contract isn't kept **.
** If the argument is incorrect, be quiet and throw an IllegalArgumentException **. that's all.
...... It's too messy, so I'll dig a little deeper. For example, suppose you prepare the following API. It takes two arguments and returns the result of a / b. (It's just an example, so please forgive me for being too much of a substitute)
ex1.java
public int div(int a, int b){
return a/b;
}
However, it was criticized that this was not good. This is because div (1,0)
will cause an ArithmeticException (it may be better to say DivideByZeroException to the people of .net, I am also a DBZE sect ...).
What would you do then? Well, we'll have validation.
The answer is, of course, "** in some cases **". This should be created if the intended use is to "catch individual exceptions together to some extent", as in the previous example. It's still unsightly to catch a lot of exceptions. Conversely, if you have no reason to make something **, you should use the existing one **. It's not difficult. In short, reinventing the wheel is ridiculous, so it's just a matter of stopping.
** Keep the contract and enjoy coding! !! ** **
Also, ** I'm asking you, so don't just imitate yourself going to destroy the type system **. (However, I think this should be said to an idiot who treats code values with raw numbers ...)
Recommended Posts