Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the bad habits java programmers should not have?

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

In view of the bad habits that java programmers should not have, this article introduces the corresponding analysis and solutions in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible way.

Only after we learn to handle exceptions can we say that we are qualified java programmers. Only after getting rid of the following six bad habits of exception handling can you deter a rookie who has just graduated. The following editor will explain how many bad habits java programmers should not have?

There are several bad habits that java programmers should not have.

OutputStreamWriterout=...

Java.sql.Connectionconn=...

Try {/ / ⑸

Statementstat=conn.createStatement ()

ResultSetrs=stat.executeQuery (

"selectuid,namefromuser")

While (rs.next ())

{

Out.println ("ID:" + rs.getString ("uid") / / ⑹

+ ", name:" + rs.getString ("name"))

}

Conn.close (); / / ⑶

Out.close ()

}

Catch (Exceptionex) / / ⑵

{

Ex.printStackTrace (); / / ⑴, ⑷

}

As a Java programmer, you should be able to identify at least two problems. However, if you can't find all six questions, please continue to read this article.

This article does not discuss the general principles of Java exception handling, as they are already familiar to most people. What we need to do is to analyze various common bad habits that violate excellent coding norms that can be called "anti-pattern", so as to help readers familiarize themselves with these typical negative examples, so that they can be acutely aware of and avoid these problems in practical work.

One of the counterexamples: discard the exception

Code: 15 lines-18 lines.

This code catches an exception without handling it, which can be regarded as a killer in Java programming. In terms of the frequency and scourge of the problem, it may be comparable to a notorious problem of the CumberCraft + program. Does not check whether the buffer is full. If you see this throwing (rather than throwing) exceptions, you can be 99% sure that there is a problem with the code (in rare cases, this code has a reason to exist, but it's best to add complete comments so as not to be misunderstood).

The mistake with this code is that an exception (almost) always means that something is wrong, or at least something unusual has happened, and we should not be silent and indifferent to the distress signal sent by the program. Calling printStackTrace is not "handling exceptions". Yes, calling printStackTrace is helpful for debugging the program, but after the program debugging phase is over, printStackTrace should no longer have the primary responsibility in the exception handling module.

It is very common to discard exceptions. When you open the document of JDK's ThreadDeath class, you can see the following description: "in particular, although the emergence of ThreadDeath is a 'normal situation', the ThreadDeath class is a subclass of Error rather than Exception, because many applications will capture all Exception and discard it." This means that although ThreadDeath represents a common problem, since many applications try to catch all exceptions and not handle them properly, JDK defines ThreadDeath as a subclass of Error, because the Error class represents a serious problem that general applications should not catch. It can be seen that the bad habit of dropping exceptions is so common that it has even affected the design of Java itself.

So, how should we correct it? There are four main options:

1. Handle exceptions. Take some actions against the exception, such as correcting the problem, reminding a person or doing some other treatment, to determine the action that should be taken according to the specific situation. Again, calling printStackTrace does not count as "handling the exception".

2. Re-throw the exception. After analyzing the exception, the code that handles the exception thinks that it cannot handle it, and it is also an option to rethrow the exception.

3. Convert the exception into another exception. In most cases, this refers to converting a low-level exception into an application-level exception (the meaning of which is more easily understood by the user).

There are several bad habits that java programmers should not have.

4. Do not catch exceptions.

Conclusion 1: since the exception has been caught, it is necessary to deal with it properly. Don't catch an exception and then throw it away and ignore it.

The second counterexample: do not specify a specific exception

Code: 15 lines.

Many times people are attracted by the "wonderful" idea of catching all exceptions with a catch statement. The most common case is the use of catch (Exceptionex) statements. But in fact, in the vast majority of cases, this approach is not worth advocating. Why?

To understand why, we must review the purpose of the catch statement. The catch statement indicates that we expect some kind of exception and want to be able to handle it. The purpose of an exception class is to tell the Java compiler what kind of exception we want to handle. Since most exceptions derive directly or indirectly from java.lang.Exception, catch (Exceptionex) is tantamount to saying that we want to handle almost all exceptions.

Let's take a look at the previous code example. What exception do we really want to catch? The most obvious one is SQLException, which is a common exception in JDBC operations. Another possible exception is IOException, because it manipulates OutputStreamWriter. Obviously, it is not appropriate to handle these two distinct exceptions in the same catch block. It would be much better to capture SQLException and IOException with two catch blocks, respectively. That is, catch statements should specify specific exception types as much as possible, rather than Exception classes that are too wide-ranging.

On the other hand, in addition to these two specific exceptions, there are many other exceptions that can also occur. For example, what if executeQuery returns null for some reason? The answer is to let them continue to throw without capture or processing. In fact, we cannot and should not catch all possible exceptions, and there are opportunities to catch exceptions elsewhere in the program. Until finally, it is handled by JVM.

Conclusion 2: specify specific exception types in the catch statement as much as possible, and use multiple catch. Don't try to handle all possible exceptions.

The third counterexample: no release of occupied resources

Code: 3 lines-14 lines.

The exception changes the normal execution flow of the program. Although this truth is simple, it is often ignored by people. If the program uses resources such as files, Socket, JDBC connections, etc., even if it encounters an exception, it should release the occupied resources correctly. To this end, Java provides a keyword to simplify this kind of operation finally.

Finally is a good thing: regardless of whether there is an exception or not, Finally ensures that the code that performs the cleanup task always has a chance to execute before the end of the try/catch/finally block. Unfortunately, some people are not used to using finally.

Of course, you should be careful when writing finally blocks, especially the exceptions thrown within finally blocks. This is the last chance to perform a clean-up task and try not to make any more intractable mistakes.

Conclusion 3: ensure that all resources are released correctly. Make full use of finally keywords.

Counterexample 4: do not describe the details of the exception

Code: 3 lines-18 lines.

Take a closer look at this code: what happens if there is an exception inside the loop? Can we get enough information to determine the cause of the error within the loop? I can't. We can only know that some kind of error has occurred in the class we are currently working on, but we cannot get any information to determine the cause of the current error.

The stack trace function of printStackTrace shows the execution flow of the program running to the current class, but only provides some basic information, fails to explain the actual cause of the error, and is not easy to interpret.

Therefore, in the event of an exception, it is best to provide some text information, such as the currently executing classes, methods, and other state information, including collating and organizing the information provided by printStackTrace in a more readable way.

Conclusion 4: provide an appropriate amount of error cause information in the exception handling module and organize the error information to make it easy to understand and read.

Counterexample 5: oversized try blocks

Code: 3 lines-14 lines.

You can often see people putting a lot of code into a single try block, which is actually not a good habit. The reason why this phenomenon is common is that some people are trying to save trouble and are unwilling to take the time to analyze which lines of code in a large piece of code will throw an exception and what the specific type of exception is. Putting a large number of sentences into a single huge try block is like stuffing all your daily items into a big box when you travel. Although you have something with you, it is not easy to find it.

Some novices often put a lot of code into a single try block and then declare Exception in the catch statement instead of separating the paragraphs that may have exceptions and catching their exceptions separately. This makes it difficult to analyze the reason why the program throws an exception, because there are too many places in a large piece of code that may throw Exception.

Conclusion 5: minimize the volume of the try block.

Counterexample 6: the output data is incomplete

Code: 7 lines-11 lines.

Incomplete data is the invisible killer of Java programs. Take a closer look at this code and consider what happens if an exception is thrown in the middle of the loop. Of course, the execution of the loop will be interrupted, and secondly, the catch block will execute. That's it. There's no other action. What about the data that has been output? The person or device that uses the data will receive an incomplete (and therefore incorrect) piece of data without any hints as to whether the data is complete. For some systems, incomplete data may cause greater loss than system shutdown.

An ideal solution is to write some information to the output device to declare the incompleteness of the data; another possible effective way is to buffer the data to be output first and then output all the data at once.

Conclusion 6: fully consider the possible exceptions and their impact on the execution process.

Rewritten code

According to the above discussion, the rewritten code is given below. Maybe some people would say it's a little bit? Wordy, but it has a relatively complete exception handling mechanism.

The answers to the questions about the bad habits that java programmers should not have are shared here. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report