Java Exception

zhaozj2021-02-12  190

Time: 2003-12-17 19:32:48 Title:

Robbin, not I know the consultant, is the post we simultaneously issued. Turn a post. I need a little time to accept your point of view. ========================================================================================================================================================================================== /2003/11/19/exceptions.html author: Gunjan Doshi 2003-11-19 Translator's Note: This article is regarded as one study notes, only to learn reference, there is something wrong, please point out. 2003-12-04 "This article is a good article handled by Exception. From the concept of Java Exception, this article introduces the type of Exception (Checked / Unchecked), the best implementation of Exception processing: 1. Select Checked or unchecked Several classic basis 2. Exception package problem 3. If there is no need to create an Exception 4. Do not use Exception to make process control 5. Do not easily ignore captured Exception 6. Do not simply capture the top of Exception - - Introduction to Javadigest.net for the original text "Javadigest.Net This site doesn't know if everyone is often, just like its name, which makes us more effective digestive Java, or it is like a transfer station, at least I am like this, some good can be said to be a very classic technical article, I have received it for the first time, more time I am lazy, Javadigest.Net, because if it is a classic article, It has a introduction of text and original connections. "- The small episode and I am very honored to recommend javadigest.net to your abnormal handling is to have to use them and how to use them. heart. In this article, I will introduce some best practices for abnormal processing, and I will also involve the use of the recent controversy of Checked Exception. As a developer, we all want to write to the problem and are high quality code. Unfortunately, some side effects (Side Effects) are accompanied by abnormal growth in our code. No doubtful, no one likes side effects, so we will use our own way to avoid it, I have seen some smart programmers to handle exceptions with the following way: public void consumeandforgetallexceptions () {TRY {... Some Code That Throws Excetions} Catch (Exception EX) {EX.PRINTSTACKTRACE ();}} What is the problem? How do we think about how to think before answering? Yes, once the program encounters an exception, it "Do" in this hangup program.

So is the code in the upper side? Look, what is it concealed? It puts all the "bitter water" into the belly (in the console printing exception information), then everything will continue, it is like nothing happened from the surface ... It is clear that the effect of the upper code is not We expect. What is it? What is the problem with the code on the PUBLIC VOID SOMETHOD () THROWS EXCEPTION {}? Obviously, the upper method is empty, it does not achieve any function (no code), what exception can I throw? Of course, Java does not stop you from doing. Recently, I also encountered a similar situation, the method statement will throw an exception, but there is no "opportunity" to "display" exception. When I asked the developer to do this, he answered me "I know, it is really a bit, but I used to do this and it really can work for me." I have spent several years in C community. To practice how to use exception, the debate about this class has just begun in the Java community. I have seen many Java programmers argue for the use of abnormal problems. If the exception is handled properly, the exception can slow down the execution speed of the application because it will consume memory and CPU to create, throw and capture exceptions. If the excessive dependent abnormality is handled, the code has an impact on the two aspects of easy reading and easy to use, so that we will write two "bad" code on the upper side. Three different "scenarios" can lead to exceptions: l PREPTION Due Programming Errors: This scenario is often in programming errors (such as: NullPointerexception or IllegarargumentException), Once the abnormality is thrown, the client will become unable to force. l Client code errors cause an exception: Bai point is that the client attempts to call the API not allowed. l Resource failure causes an exception (Exception Due to Resource Failures): If the memory is insufficient or the network connection failure causes an abnormality. These abnormal appearance clients can take corresponding steps to restore the application's continued operation. Two types of exceptions in Java in Java: l Checked Exception: This exception is an Exception subclass. L Unchecked Exception: This exception is the subclass of RuntimeException, although RuntimeException is also the subclass of Exception, but they are special, they can not by client code to try to solve, so called Unchecked exception for example, inheritance below shows a NullPointerException: Figure 1. Sample exception hierarchy diagram, NullPointerException inherited from RuntimeException, so it is Unchecked exception I used to apply CHECKED Exception more than Unchecked Exception, recently, an argument for Checked Exception and the use of their value in the Java community.

This debate originated in Java is the first fact that C and C # are not Checked Exception at all, while C and C # are not Checked Exception, all of them unchecked. A Checked Exception is forcing its client to throw and capture it. Once the client does not effectively handle these throwing exceptions, it will bring an undesirable burden to the execution of the program. Checked Exception may also bring a package leak, look at the following code: Public List getallaccounts () throws filenotfoundexception, the method on the SQLEXCEPTION {...} throws two exceptions. The client must display and handle these two exceptions even if this abnormality is completely due to file or database operation. Therefore, the abnormality processing at this time will result in an inappropriate coupling between a method and the call. Next I will give the best practices for several design abnormalities (Best PractiSs for Designing the API). When you want to decide whether you use Checked Exception or unchecked Exception, you have to ask yourself a question. "If this exception is thrown, what kind of remedies will the client do?" , Ask yourself, "What action can the client code Take when the exception tclus?"] If the client can restore an exception through other methods, then this exception is Checked Exception; if the client is an unusual power, then This exception is unchecked exception; from the use, when you have an exception, you have to try to restore its actions instead of printing its information, always, look at the table: Client's Reaction When Exception Happens Exception type client code can not do anything make it an unchecked exception client code will take some useful recovery action based on information in exception make it a checked exception Also, try to use unchecked exception to handle the programming error: because unchecked exception without making the client code shown Treat them, they will hang the program and print out abnormal information. A rich unchecked exceTpion, such as: NullPointersterexception, ILLEGALARGUMENTEXCETION, ILLEGALSTATEXCEPTION, etc., so I usually use these standards and unwilling to create new exception classes in person, so that my code is easy to understand and avoid too much. Consuming memory. 2. PRESERVE ENCAPSULATION Don't let the Checked Exception you have to thrown to a higher level. For example, don't let SQLException extend to the business layer. The business layer does not need (not concerned?) SQLEXCEPTION.

You have two ways to solve this problem: l Transform SQLException is another checked Exception, if the client does not need to restore this exception; L transform SQLException is a unchecked Exception, if the client is in powerless; In most cases, the client code is impossible to SQLException, so you have to change it into a unchecked exception, look at the following code: public void datacode () {Try {..some code That throws Sqlexception } catch (sqlexception ex) {ex.printStackTrace ();}} The catch block on the top is tightly printing exception information without any direct operation, because you also want to do what the client is to do for SQLEXCEPTION. ? (But it is clear that this is not good if there is anything like there is no way)) So there is no more feasible way? public void dataAccessCode () {try {..some code that throws SQLException} catch (SQLException ex) {throw new RuntimeException (ex);}} SQLException top approach is to convert a RuntimeException, once SQLException is thrown, then the program Throw RuntimeException, at which time the program is suspended and returned to the client exception information. If you have enough confidence to restore it when SQLException is thrown, then you can convert it into a meaningful Checked Exception, but I found that it is enough to throw RuntimeException. 3. Don't create unwanted anomalies (Try Not Create New Custom Exceptions if the do note.) Do you have any questions about the code below? Public class duplicateusernameException Exception {} It doesn't have any useful information except for a "meaning clear" name. Don't forget that Exception is the same as other Java classes, the client can call the method to get more information. We need to add a number of methods, as follows: public class DuplicateUsernameException extends Exception {public DuplicateUsernameException (String username) {....} public String requestedUsername () {...} public String [] availableNames () {.. }} There are two useful methods in the new code: reqeuestedUserName (), customers but can get the name of the request; availablenames (), the client can get a group of useful usernames. This way the client is getting the information it returns to clarify its failure.

But if you don't want to add more information, then you can throw a standard Exception: throw new exception ("UserName Already Taken"); more even, if you think the client does not want to use too much operation, just To see an exception message, you can throw a unchecked Exception: throw new runtimeException ("UserName Already Taken"); additional, you can provide a method to verify that the username is occupied. It is necessary to reiterate again, Checked Exception should get a rich information from it. To make your code more easy to read, tend to handle errors in the program with unchecked exceTPIs (Prefer Unchecked Excetions for All Programmatic Errors). 4. Document Excetions. You can explain the CHECKED Exception or Unchecked Exception in your API through the Javadoc's @throws tag (Document). However, I prefer to use the unit testing to illustrate an exception. No matter which way you use, you have to let the client code know the exceptions you have to thrown in your API. There is a testing unit to test the IndexOutOfBoundsException example: public void testIndexOutOfBoundsException () {ArrayList blankList = new ArrayList (); try {blankList.get (10); fail ( "Should raise an IndexOutOfBoundsException");} catch (IndexOutOfBoundsException success The code on the {}} will throw indexoutofboundsexception when requesting BlankList.get (10), and if it is not thrown, the fail ("Should Raise An IndexOutOfboundSException") shows that the test fails. You can not only see what the exception is working, but you can make your code get more and more robust.

The author will use the best practices in the introduction world (Best Practices for Using Excetions) 1. Always do some cleaning work (Always Clean Up After YourSelf) If you use some resources such as database connection or network connection, remember to do some cleaning work (such as shutting down database connection or network connection), if your API throws unchecked exception, you use the try-finally do the necessary cleanup: public void dataAccessCode () {Connection conn = null; try {conn = getConnection (); ..some code that throws SQLException} catch (SQLException ex) { ex.printStacktrace ();} finally {DBUtil.closeConnection (conn);}} class DBUtil {public static void closeConnection (Connection conn) {try {conn.close ();} catch (SQLException ex) {logger.error ( " Cannot Close Connection "); throw new runtimeException (ex);}}} DBUTIL is a tool class to turn off the connection. It is necessary to use the importance of Finally's importance whether it is not in the process, it will be executed. In the example on the top, close the connection in the finally, throws RuntimeException. 2 if an error occurs when the connection is turned off. Do not use exceptions to control flow (Never use exceptions for flow control) below the code, MaximumCountReachedException is used to control flow: public void useExceptionsForFlowControl () {try {while (true) {increaseCount ();}} catch (MaximumCountReachedException ex) { } // Continue execution} public void increaseCount () throws MaximumCountReachedException {if (count> = 5000) throw new MaximumCountReachedException ();} upper side useExceptionsForFlowControl () with an infinite loop to increase the count until an exception is thrown, this practice does not It is said that the code is not easy to read, but it is a decrease in program execution efficiency. Remember that exception handling is performed only if you want to throw an exception. 3. Don't ignore the exception When there is an exception thrown, if you don't want to recover it, then you have to convert it to unchecked Exception, not to use an empty catch block or not to ignore it, As for what is seen from the surface, it is not the same.

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

New Post(0)