Java really needs Checked Exception?

zhaozj2021-02-16  53

Java really needs Checked Exception?

?

Although C introduces an abnormal specification for the first time, Java is the only mainstream language that enforces the "Check Exception" specification. In this discussion, I will examine the motivation and results of this experiment, and propose another method for managing an abnormal management. The goal of this discussion is to explore this idea - especially, what is your experience? Will it be more beneficial to you using "Unchecked Exception"?

Note: You can find a related prose here.

When an exception is introduced into a C committee, I start to understand them, and this is a long learning curve. One of the primary reasons to introduce an exception is that they will make the programmer write less error check code, because these code can be placed in a more suitable place behind, rather than must be placed at each function call point - Although Few people will do it. In fact, I think: The main motivation of exception handling in C is to correct the difference in Point for C, because we really need a unified and consistent report error model (unfortunately Because C is compatible with C, the exception handling in C is only an additional error handling model).

It seems that "the exception of check" seems to be a good idea. All this is based on our untrophic hypothesis - static type check can detect your problem and always best. Java is the first language (I know) using the language of "inspection", so it turns into the first experiment. However, you must write an exception handling code in the original code, which is these common Swallowed exceptions (Zemdian Note: It is actually what we often say) makes us start thinking of this problem. In Python, the exception is not checked, and if you want, you can catch them and do something, but you are not forced. And it seems to work very well.

I believe that fundamentally speaking, this is "compile time check" with the "runtime check". We are accustomed to "compile time check" is the only correct, safe and reliable approach, and we will naturally think that "runtime check" is considered unreliable. This idea is from C , but I need to point out: Java actually made a lot of things in the run, we still accept it because they can't do it in the compile time! Despite this, we still persist: if it may be done during the compile period, this is the only appropriate time (refer to the weak type check in Python). I know this seems to be a way that is not accurate and proved; but when you have the experience of rebutting routine thinking, you can question it (don't understand? ME 2).

I started this discussion since I last summer, and I have begun to receive other people's letter, about the "exception" is an error. There is no in Python, C, C . In fact, it is said that knowing only in Java, and I will bet this because people have seen the "unchecked anomalies" specification in C and determine that is an error (I know me too, for a long time) . Based on this, I feel that "the exception of check" is (1) I haven't tried it, putting them in Java's experimental items (unless you know other languages ​​... Ada, maybe?) 2) A failed because so many people end up swallowing those exceptions. In Python / C #, exception is thrown, if you want you to write code to capture; of course, if you don't want, you will not be forced to write an extra code to swallow this exception.

I am currently planning to rewrite an exception (and other chapters), which will change the way to process anomalies, and add it to 3 (translator Note: Of course, the famous "Java programming idea) ").

I (now) thinking is like this:

1) The huge value of abnormal is that it uses a unified way to report errors: use standard mechanisms to report which error, rather than the negligible method used in C. (therefore, C , this only adds this mixture Exception, but did not make it a proprietary approach). A large advantage of Java relative to C is that its exception is the only way to report errors.

2) "Neglect" mentioned in the previous paragraph is another problem. Its theory is: If the compiler is forced to process the programmer or handle the exception, or pass it down, then the programmer's attention will be placed on the possible mistake so they will process them correctly. I think the problem is that this is only a unspecified assumption that the language designer stands in a psychological perspective. My theory is: When someone is trying to do things, you often use troubles to provoke them, then they will use the possible most convenient way to get it to drive the troubles; when they completed this Things, maybe they will return and remove this method, with arrogant look. I found that I have written this in the first edition of Java Programming Thoughts:

...

} catch (somekindofexception e) {}

In the following chapters or less forgotten (the translator's note: no compliance), until the book's reprint. But how many people think this is a good model and following it? I started reading the code associated with this and realized that people were extinct (stubbing) abnormalities and abnormalities were disappearing. The high "inspection exception" is playing with the opposite effect, and may even happen in your experience (and I now believe that "the exception" is a good idea based on someone, until I have always thought that this is a good idea).

When I started using Python, all exceptions appeared, no one will be "disappeared". If you want to catch an exception, you can, but you are not forced to write a lot of code because just to deliver an exception. They have been passed to where you want to catch them, if you forget to capture in a place, they will always go out (so they remind you), but they don't disappear, this is the most in all possible situations bad. I now believe that "the abnormal inspection" encourages people to make the abnormality disappear, and this makes the code are not read.

Finally, I think "thinking that" everything about Java is good, we must realize the "inspected exception" as the nature of the experiment and carefully check them. I believe that the use of a single mechanism to handle exception is excellent, and I believe that using a separate channel makes the abnormal movement (the abnormal processing mechanism) is also good. But I really remember that one of the early arguments of exception handling in C is that it will allow programmers to separate the work code section and the processing error code part, but according to me, "the exception of check" did not do this Instead, they (translators Note: refer to abnormal processing code) tend to break into (a lot) into your "normal work code", so this is a reverse. I use Python unusual experience to support my point of view, and Unless I get Turned Around on this questionie I intend to put a lot more runtimeexceptions Into my java code is very clear, especially because Python: The more you have a stack of regulations to programmers, especially some regulations that don't help solve existing issues, the lower the production efficiency of programmers. And this factor does not seem to be linear, but an index level.

I have one or two reports that "in the industrial grade code," Exceptions "is a big problem, so they want to change this situation. In your opinion, most programmers with this idea may only be classified as beginners. But I have seen this situation again in the study class - people with many years of programming experience don't even understand some of the most basic things.

Perhaps this is just a matter of time. When an abnormality is introduced to the C committee, I started to understand the unusual idea (IDEA) and I have finally realized it for a long time. (And After this Much Time It Suddenly Hit Me.) And I am aware that it is used in a language that has an abnormality, but it is not an "exception to check." I think it is two complete beauty - if I want to catch an abnormality, I can, but I have not been forced to just write a lot of code and swallow it. If I don't want it, I ignore them. If there is really an exception, it will report to me during debugging, and then I will decide how to handle it. I still have an exception, but I have not been forced to write a string of code for an exception.

This is a tool I developed with HEINZ Kabutz. It converts all "inspections" into a runtimeException while still retaining all information about "checking exception".

Import java.io. *;

Class ExceptionAdapter Extends RuntimeException {

? private final string stacktrace;

PUBLIC EXCETION OriginalException;

PUBLIC EXCEPTIONADAPTER (Exception E) {

??? super (e.tostring ());

??? OriginalException = E;

??? StringWriter SW = new stringwriter ();

??? E.PrintStackTrace (New PrintWriter (SW));

??? stacktrace = sw.toString ();

?

PUBLIC VOID PRINTSTACKTRACE () {

????printstacktrace (system.err) ;?}

PUBLIC VOID PRINTSTACKTRACE (Java.io.PrintStream S) {

???? synchronized (s) {

????? s.print (getClass (). getName () ":");

????? s.print (stacktrace);

???}

?

PUBLIC VOID PRINTSTACKTRACE (Java.io.PrintWriter s) {

???? synchronized (s) {

????? s.print (getClass (). getName () ":");

????? s.print (stacktrace);

???}

?

PUBLIC VOID RethRow () {throw OriginalException;

}

?

The original exception is stored in OriginalException, so you can always restore it. In addition, the Stack TRACE information is extracted and placed in the string variable stacktrace, so it will be printed using PrintStackTrace (), and if the exception has not captured and arrived to the console. However, you can also place a catch statement at the higher level of your program to capture the ExceptionAdapter, then find a specific exception, as shown below:

Catch (ExceptionAdapter EA) {

? try {

??? ea.Rethrow ();

?} Catch (IllegaLaRgumentException E) {

??? // ...

?} catch (filenotfoundexception e) {

??? // ...

?

? // ETC.

}

Here, you can still seize a specific type of exception, but you are not forced to write all anomalous instructions and try-catch statements between abnormal sources and captured anywhere. More important, no one is trained (Tempted) Swallow This exception, then remove it. If you forget to catch some exceptions, it will pass it up. If you want to pass a certain middle, you can also.

Or, because OriginalException is public, you can also find a type of exception by means of RTTI.

This is some test code, just guarantees the above examples (but, this is not the way I suggested):

Public class exceptionAdapterTest {

PUBLIC Static void main (string [] args) {

??? Try {

????? try {

??????? throw new java.io.filenotFoundException ("Bla");

?????} catch (exception ex) {

??????? EX.PrintStackTrace ();

??????? throw new ExceptionAdapter (ex);

?????} ??

????} catch (runtimeException e) {

????? E.PrintStackTrace ();

???}

??? System.out.println ("That's all!");

?

}

With this tool, you can enjoy the benefits of "unchecked anomalies" (fewer, clearer code), and we will not lose core information about this exception.

If you want to throw some type of "check exception" in your code, you can use ExceptionAdapter below (if it is not suitable, you can modify it) :? if (Futzedup)

??? throw new exceptionadapter (new clonnotsupportedException ());

?

This shows that you can use the "unchecked exception" programming style, easy to use all of its original roles.

?

Translator Note:

1, ?????????? This article presents: When you are ready to throw an exception, you can try to package it in the ExceptionAdapter object and throw this object. In this way, although a method throws an exception, it is not necessary to capture in the method called it, because the parent class of the ExceptionAdapter object is RuntimeException, and RuntimeException is not checked;

2, ?????????? This article is explored, forever. Because I was watching C # in a recent time, I don't understand why I abandoned Java in C # I thought it was absolutely abnormal, so I found this article;

3, ?????????? I translated this article and didn't mean that I support it. Take this! !

转载请注明原文地址:https://www.9cbs.com/read-19768.html

New Post(0)