CodeWeblog.com » java sql,sql connection,anomaly » Six of the bad habits of exception handling

Six of the bad habits of exception handling

Do you think it is a Java expert right? Sure they have complete control of the Java exception handling mechanism? The code below, you can quickly identify the six exception handling problem?

1 OutputStreamWriter out = ...
2 java.sql.Connection conn = ...
3 try (/ / ⑸
4 Statement stat = conn.createStatement ();
5 ResultSet rs = stat.executeQuery (
6 "select uid, name from user");
7 while (rs.next ())
8 (
9 out.println ( "ID:" + rs.getString ( "uid") / / ⑹
10 ", name:" + rs.getString ( "name"));
11)
12 conn.close (); / / ⑶
13 out.close ();
14)
15 catch (Exception ex) / / ⑵
16 (
17 ex.printStackTrace (); / / ⑴, ⑷
18)

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

This article discusses the Java exception handling is not the general principles, as they have been known to most people. We want to do is analyze what might be called "counter-examples" (anti-pattern) coding of the violation of norms of good common bad habits to help the reader familiar with the classic negative example, which can work in practice acutely aware of and avoid these problems.

One counter-example: discard abnormal

Code: 15 line -18 line.

This code does not capture any unusual handling, can be considered the killer of Java programming. Problems arise from the frequency and extent of the scourge, it may be, and C / C + + program, a notorious problem in the same breath?? Does not check whether the buffer is full. If you see such discarded (not out) anomaly can be 99% certain code problems (in rare cases, this code there are reasons, but the best with a complete Notes, in order to avoid any misunderstanding of others).

This error code is unusual (almost) always means that some things wrong, or at least some unusual things, we should not be issued a distress signal process to remain silent and indifferent. PrintStackTrace not call you "to deal with anomalies." Yes, printStackTrace calls for debugger help, but after the debugging phase, printStackTrace on should not be in the exception handling module has the primary responsibility.

Discarded abnormal situation is very common. Open JDK documentation of ThreadDeath category, you can see this note the following: "In particular, ThreadDeath Although there is a 'normal situation', but ThreadDeath category of Error rather than Exception subclass, because many applications will capture all The Exception and then discard it is no longer ignore. "This means that, although the representative of ThreadDeath is a common problem, it will be many applications in view of all the anomalies and then trying to capture is not appropriate to deal with, so defined ThreadDeath the JDK a subclass of Error because Error category represents the application of the general should not be a serious problem to capture. Visible, discard the bad habit of anomalies are so common that it has even affected the design of Java itself.

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

1, to deal with anomalies. For the unusual number of actions, such as to fix the problem, to remind a person or some other deal, it is necessary to determine the specific circumstances of the action should be taken. Is another indication that call printStackTrace not have been "an exceptionally good deal."

2, re-thrown. To deal with unusual anomalies in the analysis after the code that they can not handle it, and re-out option may well be an anomaly.

3, the conversion into another unusual abnormality. In most cases, this means a low-level application-level anomaly into abnormal (meaning the user more easily understand the anomaly).

4, do not catch the exception.

Conclusion: Since the capture of the anomaly, it is necessary to deal with it properly. Do not catch it again later discarded, ignored.

The second counter-example: do not specify a specific abnormality

Code: 15 lines.

Many times people will be such a "wonderful" idea to attract: a catch phrase to capture all of the anomalies. The most common situation is to use catch (Exception ex) statements. But, in fact, in most cases, this approach should not be advocated. Why?

To understand its causes, we must look at the use of catch statement. catch statement that we expect there will be some kind of anomaly, and hope to be able to deal with the anomaly. Abnormal type of role is to tell the Java compiler that we want to deal with what kind of anomaly. Due to the vast majority of abnormalities are java.lang.Exception directly or indirectly derived from, catch (Exception ex) is equivalent to say that we want to deal with almost all the anomalies.

Come take a look at the preceding code example. We really want to capture what is it abnormal? The most obvious one is the SQLException, it is common JDBC abnormal operation. Another possibility is abnormal IOException, because it needs to operate OutputStreamWriter. Clearly, in the same catch block to deal with two distinct anomalies is not appropriate. Catch block if the two were caught SQLException and IOException will be much better. That is to say, catch statement should be specified as far as possible the specific type of exception, rather than specify the scope of the Exception category is too broad.

On the other hand, in addition to these two specific abnormalities, there are also many other anomalies that may arise. For example, if for some reason, executeQuery returned null, how to do? The answer is to allow them to continue to out, or do not have to deal with do not have to capture. In fact, we can not and should not be possible to capture all the anomalies, there are procedures in other parts of the opportunity to catch the exception?? Until the final deal by the JVM.

Conclusion: In the catch statement as far as possible, a specific type of abnormality and, if necessary, the use of multiple catch. Do not try to deal with all the anomalies that may arise.

The third counter-example: the release of resources are not occupied

Code: -14 line, line 3.

Abnormal changes in the procedures for the implementation of the normal process. The reason is simple, but often overlooked. If the program uses the file, Socket, JDBC connectivity, such as resources, even in the face of the anomaly, but also the right to release the resources occupied. To this end, Java provides a simplified operation of the key word of these finally.

finally is the kind of good things: no matter whether there was abnormal, Finally to ensure that try / catch / finally block before the end of the implementation of clean-up tasks always have the opportunity to implement the code. Unfortunately some people are not accustomed to using finally.

Of course, the finally block should be prepared more carefully, especially in the finally block to the attention of the abnormal out?? This is the task of the implementation of clean-up the last chance as far as possible should not be difficult to deal with mistakes.

Conclusion three: to ensure that all resources are properly released. Finally make full use of keywords.

Counter-examples of the four: do not explain the details of abnormal

Code: -18 line, line 3.

Careful observation of the code: If there were abnormal cycle, what will happen? We can get enough information to determine the cause of the internal cycle of it? Can not. We can only know the class is currently dealing with some kind of error occurred, but it can not obtain any information to determine the cause of the error led to the current.

printStackTrace function of the stack trace shows the current type of program to run the implementation process, but only provided some basic information, can not explain the actual cause of your error, but also difficult to interpret.

As a result, abnormal, it is best able to provide some text information, such as the implementation of the category currently, methods, and other status information, including in a manner more suitable for reading printStackTrace collate and organize the information provided.

Conclusion Four: In the exception handling module to provide adequate reasons for the error information, organizational error message easier to understand and read it.

Five counter-examples: the try block is too large

Code: -14 line, line 3.

Some people can often see a lot of code to a single try block, in fact, this is not a good habit. Common reason for this phenomenon, the reasons is that some people plan easier, do not want to spend time analysis of a large piece of code which threw out a few lines of code will be abnormal, the specific type of anomaly is. To a large number of statements into a single huge block like try to go out all day-to-day travel into a big box of supplies, although things are put on, but not easy to find out.

Some often a lot of new code into a single try block, and then a statement in the catch statement Exception, rather than the possible abnormal separation of the various paragraphs and abnormal, respectively, of their capture. Procedures for the analysis of this out the reasons for abnormal difficult, because a large segment of code there are too many places may be thrown Exception.

V. Conclusion: try to minimize the size of block.

Six counter-examples: incomplete output data

Code: -11 line 7 line.

Incomplete data is invisible killer Java program. Careful observation of this code, consider if the middle circle out of the anomaly, what will happen. Of course, the implementation cycle is to be interrupted, followed, catch block will be the implementation?? On these, no other action has been. How the output data has been done? The use of these data or the device will receive an incomplete (and thus wrong) data, but no complete data on this advice. For some systems, data may not be complete cessation of operation of the system brought about by greater losses.

The disposal of a better way is to write some of the information output device, the statement is not the integrity of data; Another approach may be effective, the first buffer to the output data, all data is ready after a one-time output.

VI Conclusion: taking full account of possible anomalies and the abnormal effects of the implementation process.

After rewriting the code

According to the above discussion, the following code is given after the rewrite. Maybe some people would say it is a little bit? Winded, but it has a more complete mechanism for exception handling.

OutputStreamWriter out = ...
java.sql.Connection conn = ...
try (
Statement stat = conn.createStatement ();
ResultSet rs = stat.executeQuery (
"select uid, name from user");
while (rs.next ())
(
out.println ( "ID:" + rs.getString ( "uid") + ", Name:" + rs.getString ( "name"));
)
)
catch (SQLException sqlex)
(
out.println ( "Warning: the data is incomplete");
throw new ApplicationException ( "read data when SQL error", sqlex);
)
catch (IOException ioex)
(
throw new ApplicationException ( "write data when IO error", ioex);
)
finally
(
if (conn! = null) (
try (
conn.close ();
)
catch (SQLException sqlex2)
(
System.err (this.getClass (). GetName () + ". Mymethod - can not close the database connection:" + sqlex2.toString ());
)
)

if (out! = null) (
try (
out.close ();
)
catch (IOException ioex2)
(
System.err (this.getClass (). GetName () + ". Mymethod - can not close the output file" + ioex2.toString ());
)
)
)

The conclusions of this paper is not a size-fits-all dogma, sometimes common sense and experience is the best teacher. If you do not own one hundred percent confidence in practice, be sure to add detailed and comprehensive notes.

On the other hand, these errors do not joke, you may wish to ask whether they really broken free from these bad habits. Even the most experienced programmers occasionally go astray, for the simple reason, because they indeed bring the "convenience." All of these counter-examples can be seen as a Java programming world, the devil, they beautiful, all-pervasive, at all times to tempt you. Some people may think that these are minor skin garlic hair, not worth mentioning, but remember: do not be small and in bad, not good for small.

-------------------------------------------------- ---------------- Here are some unusual set java ---------------------------- -------------------------------------------------- -------------

Abnormal types of arithmetic: ArithmeticExecption

Null pointer exception classes: NullPointerException

Abnormal type cast: ClassCastException

Abnormal negative array subscript: NegativeArrayException

Cross-border abnormal array subscript: ArrayIndexOutOfBoundsException

Abnormal security breach: SecturityException

Anomaly has been concluded: EOFException

File Not Found anomaly: FileNotFoundException

String is converted to digital anomalies: NumberFormatException

Abnormal operation of the database: SQLException

Input and output anomalies: IOException

Method is not unusual to find: NoSuchMethodException

java.lang.AbstractMethodError

Abstract methods. When an application attempts to call out the abstract methods.

java.lang.AssertionError

Wrong assertion. Used to indicate a failed assertion.

java.lang.ClassCircularityError

Rely on the wrong type of cycle. A class in the initialization, if the testing cycle of dependence between the categories are out of the anomaly.

java.lang.ClassFormatError

Class format error. When the Java Virtual Machine attempts to read a file from the Java category, and to detect the contents of the document is not consistent with the type of effective out format.

java.lang.Error

错误. For all the wrong base class, used to identify the program to run a serious problem. These problems are usually described in a number of applications should not be caught in unusual circumstances.

java.lang.ExceptionInInitializerError

Initialization Error. When implementing a static class initialization procedure, the occurrence of the abnormal out. Static initialization procedure is directly included in the class above the static statement.

java.lang.IllegalAccessError

Illegal access error. When an application attempts to access, modify a domain type (Field) or call its methods, but also in violation of the domain of visibility or method declaration, then dished out the anomaly.

java.lang.IncompatibleClassChangeError

Incompatible changes in the wrong category. When the method is dependent on the implementation of the class definition incompatible changes, out of the anomaly. General application in the revised statement of the definition of certain types without recompilation of the entire application running directly under the risk of the error.

java.lang.InstantiationError

Examples of error. When an application attempts to Java-to construct a new operator interface or abstract class out of the anomaly.

java.lang.InternalError

Internal error. Instructions for the Java virtual machine internal error occurred.

java.lang.LinkageError

Link error. The error and all its sub-class of a category of instructions dependent on some other categories, in such compilers, have been dependent on the type of change in the definition of its type without re-compiling all of the categories, which lead to mistakes.

java.lang.NoClassDefFoundError

Class definition not found error. When the Java Virtual Machine classloader, or attempt to instantiate a class, but can not find out the definition of such an error.

java.lang.NoSuchFieldError

Domain does not exist error. When trying to access or modify the application of a certain domain, and the definition of such is not the definition of the domain out the error.

java.lang.NoSuchMethodError

Method does not exist error. When an application attempts to call a certain method, and the definition of such methods is not the definition of the error out.

java.lang.OutOfMemoryError

Insufficient memory error. When available memory is not sufficient to allow Java virtual machine, when assigned to an object thrown out the error.

java.lang.StackOverflowError

Stack overflow error. When an application level of recursive calls caused by too much time out of the stack overflow error.

java.lang.ThreadDeath

End thread. When you call stop method of Thread class, when out of the wrong end of the thread for instructions.

java.lang.UnknownError

Unknown error. Instructions for the Java Virtual Machine serious error occurred in the case of the unknown.

java.lang.UnsatisfiedLinkError

Link error unmet. When the Java virtual machine not found a type of statement methods for native machine language of the definition out.

java.lang.UnsupportedClassVersionError

Version does not support the type of error. When the Java Virtual Machine attempts to read a class file, but found that the main document, sub-version number is not in support of the current Java virtual machine, the thrown out the error.

java.lang.VerifyError

Validation error. When the validator detects the existence of a certain type of file is not compatible or internal security issues out the error.

java.lang.VirtualMachineError

Virtual Machine mistake. Virtual machine instructions for the destruction of or continue to implement the necessary resources to operate underemployment.

java.lang.ArithmeticException

Arithmetic abnormal conditions. For example: In addition to zero, such as an integer.

java.lang.ArrayIndexOutOfBoundsException

Cross-border abnormal array index. When an array index value is negative or greater than or equal to the size of the array out.

java.lang.ArrayStoreException

Abnormal storage array. To the storage array when the non-array type of object statement thrown out.

java.lang.ClassCastException

Abnormal type of modeling. Assume that type A and B (A is not the father of B-type or sub-class), O is an example of A, then when forced to be O-type structure as an example of B out of the anomalies when. The anomaly is often referred to as the mandatory conversion abnormal.

java.lang.ClassNotFoundException

Type of anomaly can not find. When an application attempts to form the basis of the class name string type structure, while in CLASSPAH after traversal of the class can not find the corresponding file name, out of the anomaly.

java.lang.CloneNotSupportedException

Abnormalities do not support cloning. When there is no realization or does not support the Cloneable interface cloning method, call its clone () method out of the anomaly.

java.lang.EnumConstantNotPresentException

Enumeration constant anomaly does not exist. When an application attempts to access the name and an enumerated type enumeration, but does not contain the constant enumeration object when thrown out of the anomaly.

java.lang.Exception

Root anomaly. Application to describe the situation in hope to capture.

java.lang.IllegalAccessException

Visit abnormal offenders. When an application attempts to create a reflection-type examples, visit these properties, call these methods, and there was also unable to access class, attribute, method or constructor definition out of the anomaly.

java.lang.IllegalMonitorStateException

Abnormal state of illegal surveillance. When a thread attempts to wait for a target of himself does not own (O) of the monitor or notify other threads waiting for the object (O) when the monitor, out of the anomaly.

java.lang.IllegalStateException

Abnormal state of the law. When the Java application environment and has not been in a legitimate way to call the state, and call the method, out of the anomaly.

java.lang.IllegalThreadStateException

Abnormal state of the law of the thread. When the county has not yet been in a legitimate way to call the state, and call the method, thrown.

java.lang.IndexOutOfBoundsException

Index of cross-border anomalies. When to visit a sequence of index values of less than 0 or greater than or equal to the size of sequence, out of the anomaly.

java.lang.InstantiationException

Examples of anomalies. When trying to newInstance () method to create a kind of example, and such is an abstract class or interface, the out of the anomaly.

java.lang.InterruptedException

Abnormalities have been suspended. When a thread in a long time of waiting, dormant or otherwise inactive, while the other thread through the Thread of the interrupt method to terminate the thread out of the abnormal.

java.lang.NegativeArraySizeException

Negative abnormal size of the array. When using a negative value to create the array when the size of the abnormal out.

java.lang.NoSuchFieldException

There is no unusual properties. When access to a category does not exist out of the unusual attributes.

java.lang.NoSuchMethodException

Method does not exist abnormal. When access to a class method that does not exist out of the anomaly.

java.lang.NullPointerException

NULL pointer abnormal. When an application attempts to require the use of objects in use when a null, out of the anomaly. For example: null call object methods, visit the properties of null objects, computing the length of null objects, null out the use of throw statements and so on.

java.lang.NumberFormatException

Abnormal digital format. When trying to convert a String to specify the number of types, and the string type does does not meet the requirements of the digital format, out of the anomaly.

java.lang.RuntimeException

Run-time anomaly. All the Java virtual machine during normal operation can be dished out by the parent anomaly.

java.lang.SecurityException

Security anomalies. Dished out by the security manager for breach of the safety instructions of the abnormal situation.

java.lang.StringIndexOutOfBoundsException

String index cross-border anomalies. When using the index value to access a string of characters, and the index value is less than 0 or greater than or equal to the size of sequence, out of the anomaly.

java.lang.TypeNotPresentException

The type of anomaly does not exist. When an application attempts to string the name of a certain type of access to this type of expression, but in accordance with the given name and can not find out the type of the anomaly. The anomaly and the difference is that the ClassNotFoundException exception is unchecked (not checked) anomaly, and ClassNotFoundException is checked (checked) anomaly.

java.lang.UnsupportedOperationException

Anomaly does not support the method. Method specified in the request to support the situation is not unusual.

Abnormal
javax.servlet.jsp.JspException: Cannot retrieve mapping for action / Login (/ Login name is your action)

Possible reasons for
no further action as defined in struts-config.xml, or did not find matching action, such as the use of the JSP file <html: form action = "Login.do". will be submitted to the Login.do form, if the above-mentioned abnormal , see the struts-config.xml in the definition of some, it may sometimes be wrong characters or not in conformity with certain rules, you can use the tool to check strutsconsole.
-------------------------------------------------- -------------------------------------------------- -------------
Abnormal
org.apache.jasper.JasperException: Cannot retrieve definition for form bean null

Possible reasons for

This anomaly is because the Struts based on struts-config.xml in the action of the mapping does not expect to find the form bean. Most cases may be due to the form-bean to set the name attribute and action setting the name attribute does not match the result of. In other words, action and form should have a name of their respective properties, and to exact match, including case. This error when there is no name attribute and the action will occur when the correlation, if there is no action specified in the attribute name, then there is no name attribute and the associated action. Of course, when the production of certain control action, such as parameter values in accordance with the corresponding jsp Jump to page, rather than dealing with form data, which is on the do not have name attributes, which is the use of action methods.
-------------------------------------------------- -------------------------------------------------- -------------
Abnormal
No action instance for path / xxxx could be created

Possible reasons for
Special Note: Because there are many in the situation will lead to the occurrence of this error, so we recommend to increase your web server's log / debug level, so that more information can see the potential, in the attempt to create a type of action occurred error, the action type you have in the struts-config.xml to set up a link (that is, <action> added label).

In the struts-config.xml in the class through the action label of the action attribute type can not be found there are many reasons, such as: positioning compiled. Class files failed. Failure to place compiled. Class file for the action in the classpath (in the web development, class position in the r WEB-INF/classes, so you must be the action class in the directory. For example, you type the action is located in WEB -INF/classes/action/Login.class, then in the struts-config.xml to set the attribute type when the action is action.Login).
Spelling errors, which occur from time to time, and difficult to find, with particular attention to the first letter of the case and the package name.
-------------------------------------------------- -------------------------------------------------- -------------
Abnormal
javax.servlet.jsp.JspException: No getter method for property username of bean org.apache.struts.taglib.html.BEAN

Possible reasons for
There is no place in the form bean definition of a variable getter method

This error occurs mainly in the form submitted by FormBean in <html:text property="username"> using struts tags when there is a FormBean must getUsername () method. Attention to the letter "U".
-------------------------------------------------- -------------------------------------------------- -------------
Abnormal
java.lang.NoClassDefFoundError: org / apache / struts / action / ActionForm

Possible reasons for
This error occurs mainly in the classpath can not be found in the corresponding Java. Class files. If this error occurred in the web application run-time, mainly because the class file is not specified web server's classpath in the (/ WEB-INF/classes and / WEB-INF/lib). In the above mistakes, the reasons for that category can not find ActionForm.
-------------------------------------------------- -------------------------------------------------- -------------
Abnormal
javax.servlet.jsp.JspException: Exception creating bean of class org.apache.struts.action.ActionForm: (1)

Possible reasons for
Instantiating Struts-provided ActionForm class directly instead of instantiating a class derived off ActionForm. This mightoccur implicitly if you specify that a form-bean is this Struts ActionForm class rather than specifying a child of this classfor the form-bean.

Not associating an ActionForm-descended class with an action can also lead to this error.
-------------------------------------------------- -------------------------------------------------- -------------
Abnormal
javax.servlet.jsp.JspException: Cannot find ActionMappings or ActionFormBeans collection

Possible reasons for
Rather than the Struts actionServlet logo is <servlet> tag mapping. Do extension or both markers <sevlet-mapping> not stated in the web.xml.

Struts-config.xml in the typing or spelling errors can also lead to the occurrence of this anomaly. For example, the closure of the lack of a marker symbol />. The best tools to use to check struts console.

In addition, load-on-startup in web.xml must be stated that this is either an empty tag, or specify a value, this value is used to form the priority of running servlet, the greater the value the lower priority.

And the use of a load-on-startup is to use the Struts-related pre-compiled JSP files may also lead to this anomaly.
-------------------------------------------------- -------------------------------------------------- -------------
Abnormal
java.lang.NullPointerException at org.apache.struts.util.RequestUtils.forwardURL (RequestUtils.java: 1223)

Possible reasons for
In the struts-config.xml in the path attribute the lack of forward elements. For example, the form should be as follows:
<forward name="userhome" path="/user/userhome.jsp"/>
-------------------------------------------------- -------------------------------------------------- -------------
Abnormal
javax.servlet.jsp.JspException: Cannot find bean org.apache.struts.taglib.html.BEAN in any scope

Probable Causes
Struts trying to use the form tag outside the form of sub-elements. This often happen to you in </ html: form> after using the Struts-html tag. In addition you may inadvertently pay attention to the use of the main body of the tag-free, such as <html:form… />, so when the web server to resolve the main body as a marker, and then use all <html> tags are considered to be in this outside marker, such as the use of <html:text property="id"> Also there is the introduction of the use of HTML tags taglib library, you use the prefix value is not html.
-------------------------------------------------- -------------------------------------------------- -------------
Abnormal
javax.servlet.jsp.JspException: Missing message for key xx.xx.xx

Probable Causes
The value of this key resource document for ApplicationResources.properties not defined. If you use eclipse often encountered such a situation, when the project to re-compile-time, eclipse will automatically classes directory to delete the resource file.

Classpath resource file is not ApplicationResources.properties resource file should be placed in the WEB-INF/classes directory, of course, in the struts-config.xml to define)
-------------------------------------------------- -------------------------------------------------- -------------
Abnormal
Cannot find message resources under key org.apache.struts.action.MESSAGE

Possible reasons for
It is clear that this error occurred in the use of resources, documents, and Struts do not find resource file.

Implicitly trying to use message resources that are not available (such as using empty html: options tag instead of specifyingthe options in its body - this assumes options are specified in ApplicationResources.properties file)

XML parser issues - too many, too few, incorrect / incompatible versions
-------------------------------------------------- -------------------------------------------------- -------------
Abnormal
Strange and seemingly random characters in HTML and on screen, but not in original JSP or servlet.

Possible reasons for
Mixed use Struts-html: form tag and the standard HTML tag is not correct.

Coding style used is not supported on this page.
-------------------------------------------------- -------------------------------------------------- -------------
Abnormal
"Document contained no data" in Netscape

No data rendered (completely empty) page in Microsoft Internet Explorer

Possible reasons for
Action of the use of a derived class but not the achievement of perform () method or execute () method. Struts1.0 to achieve in the perform () method to achieve Struts1.1 is execute () method, but Struts1.1 backwards compatibility perform () method. However, you create an Action using the Struts1.1 derived class, and the realization of the execute () method, and you run Struts1.0, they would get "Document contained nodata" error message in Netscape or a completely empty (no HTML whatsoever) page rendered in Microsoft Internet Explorer. "error message.

-------------------------------------------------- -------------------------------------------------- -----------------------
Abnormal
ServletException: BeanUtils.populate
Solutions
Upload files using Struts encountered a javax.servlet.ServletException: BeanUtils.populate abnormal.
ActionServlet I did not use these tools BeanUtils. Double-check the code later found to be in the jsp file form forgot to add the enctype = & amp; quot; multipart / form-data "has been. Therefore, the procedure was unusual to encounter an error or a problem from different perspectives to consider the possibility, I was thinking about the system other than a message.
-------------------------------------------------- -------------------------------------------------- ------------------------
1. The definition of Action, if the specified name, then need to define a FormBean with the same name in order to form mapping .2. If, after the definition of Action, when submitted to the page "No input attribute for mapping path ..." error, you need to input attribute in its definition of page turning .3. if inserted when new data "Batch update row count wrong :..." error, then XXX.hbm.xml specified in the original key is of type type (int, long), because this type will be automatically assigned value, and the value systems that often make the record already exists, the correct approach is to use java.lang.Integer or java.lang.Long object .4. If you insert when the data "argument type mismatch" error, you may be using the Date object, such as special as the struts can not automatically convert from the String type Date type, so you need to manually put in the Action type String into a Date type .5 . Hibernate in, Query of the iterator () than the list () method is much faster .6. if there is "equal symbol expected" error to show that you can label strtus included in the labeling or other variables, such as:
<html: select property = "test" onchange ="<%= test %>"/>
Either
<html: hidden property = "test" value = "<bean:write name="t" property="p"/>" />
That being the case ...
-------------------------------------------------- -------------------------------------------------- -----------------------
Error: Exception in thread "main" org.hibernate.exception.SQLGrammarException: Could not execute JDBC batch update the reasons and solutions: The Hibernate Tools (or Eclipse itself Database Explorer) tool to generate *. hbn.xml contains catalog = " that the database name ***"(*) such properties, the properties can be deleted
-------------------------------------------------- -------------------------------------------------- -----------------------
Error: org.hibernate.ObjectDeletedException: deleted object would be re-saved by cascade (remove deleted object from associations)
Reasons and solutions:
Method 1's cascade delete Set
Method 2 to resolve relationship and then delete
Method 3 in the many-to-one to increase the value of cascade but can not be none
Last resort:
HashCode equals check whether or not to use the id as the only option has been marked; uuid.hex I am is no problem; but with a native, on the point of death, how should I do? Delete ah!
-------------------------------------------------- -------------------------------------------------- ------------------------
Question: Today, Tomcat 5.5.12, found that good systems can not be used, and repeated tests found that the page can not contain taglib, otherwise they will be prompted the following: HTTP Status 500-type Exception reportMessage description The server encountered an internal error ( ) that prevented it from fulfilling this request.exceptionorg.apache.jasper.JasperException: / index.jsp (1,1) Unable to read TLD "META-INF/tlds/struts-bean.tld" from JAR file "file: * ****/ WEB-INF/lib/struts.jar ": reasons: to update the project with the lib folder of the jar, also issued a release servlet.jar and jsp-api.jar. Solution: to delete the jsp-api.jar to solve this problem. -------------------------------------------------- -------------------------------------------------- -------------------------
Error: java.lang.NullPointerException
Reasons: dao instance found, manage, etc. Examples of things that do not need to be injected into the (commonly known as a null pointer exception) solution: this time, you should view the log file; default is the application server log files, such as the Tomcat is the [Tomcat installation directory] / logs; tips you will find that you: may be: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sf' defined in ServletContextresource [/ WEB-INF/applicationContext.xml]: Initialization of bean failed; nested exception isorg.hibernate.HibernateException: could not configure from URL: file: src / hibernate.cfg.xmlorg.hibernate.HibernateException: could not configure from URL: file: src / hibernate.cfg.xml ... ... ... ... ... ... ... ... ... . Caused by: java.io.FileNotFoundException: src \ hibernate.cfg.xml may be: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined inServletContext resource [/ WEB-INF/applicationContext.xml ]: Initialization of bean failed; nested exception isorg.hibernate.MappingException: Resource: com / mcc / coupon / model / UserRole.hbm.xml not foundorg.hibernate.MappingException: Resource: com / mcc / coupon / model / UserRole.hbm . xml not found then you will know the reason is because the configuration file of the wrong resolution, the adoption of Web pages is not out to see. More alluding to document a persistent error; led not be resolved; of course, the functions you need can not be used.
-------------------------------------------------- -------------------------------------------------- ------------------------
Error: StandardWrapperValve [action]: Servlet.service () for servlet action threw exception
javax.servlet.jsp.JspException: Cannot retrieve mapping for action / settlementTypeManage
Or: type Status report message Servlet action is not available description The requested resource (Servlet action is not available) is not available.
Reasons: Ibid
-------------------------------------------------- -------------------------------------------------- ------------------------
Error StandardWrapperValve [jsp]: Servlet.service () for servlet jsp threw exceptionjava.lang.ClassNotFoundException: org.apache.struts.taglib.bean.CookieTei interface specific description of the error:
org.apache.jasper.JasperException: Failed to load or instantiate TagExtraInfo class: org.apache.struts.taglib.bean.CookieTei
Causes and solution: <program a> your "html:" at the beginning of the label did not put in a <html:form> <Option II> Restart your application server, not the problem automatically
Digg Technorati StumbleUpon Mixx del.icio.us Reddit BlinkList Furl YahooMyWeb feedburner

Tags: java sql (RSS), sql connection (RSS), anomaly (RSS), java programmer (RSS), conn (RSS), printstacktrace (RSS), c program (RSS), programming problems (RSS), java expert (RSS), java programming (RSS), java exception handling (RSS), notorious problem (RSS), getstring (RSS), distress signal (RSS), unusual things (RSS), bad habits (RSS), rare cases (RSS), general principles (RSS), scourge (RSS), complete control (RSS)

Permalink: http://www.codeweblog.com/six-of-the-bad-habits-of-exception-handling/

Leave a reply