in the development of university projects, do you find that your own projects are always bug-not only bugs, but also difficult to find the source of the exception based on the exception information. I was also very annoyed, terrible is not know how to maintain ... Software Java anomalies need to understand the basic knowledge, in the actual combat to better deal with anomalies. Java exception basics, trycatchfinally statement blocks This section summarizes the issues related to Java exceptions in practice
1. Clean up resources in finally or use Try-with-resource statements
do not close the resource in try, because the resource cannot be shut down properly once an exception occurs. The following code gives two processing scenarios, finally closes the resource, Try-with-resource (JDK1.7 appears)
/**Write Data **/ Public Static voidWriteFile (file file) {outputstream OS=NULL; Try{OS=Newfileoutputstream (file); String Str=NewString ("Hello gay!"); //os.write (str); not coded--errorOs.write (Str.getbytes ());//Follow the default GBK encodingOs.write (5); Os.flush (); } Catch(Exception e) {e.printstacktrace (); }finally{ Try{os.close (); } Catch(IOException e) {e.printstacktrace (); } }
/**Write Data **/ Public Static voidWriteFile (file file) {//it automatically shuts down after the try is executed, or handles an exception. Try(OutputStream os=Newfileoutputstream (file)) {String str=NewString ("Hello gay!"); Os.write (Str.getbytes ());//Follow the default GBK encodingOs.write (5); } Catch(Exception e) {e.printstacktrace (); } }
2, give accurate information of abnormal handling
as much as possible to describe your exception handling information, such as using numberformatexception instead of illegalargumentexception, to avoid throwing a non-specific exception. The catch statement block is a subclass of the former and the parent class behind.
Public void throws Exception { }publicvoidthrows numberformatexception { }
3. Record Custom Exceptions
to clarify the exception information for callers and maintainers, be sure to add a @throws declaration in Javadoc and describe the possible exception conditions
/**@throws*/publicvoid throws mybusinessexception { ...}
4. Record abnormal information
Use 1-2 short sentences to explain the cause of the exception, log files
Try { new Long ("abc"catch (NumberFormatException e) { log.error ( New Exception ("xxx", E));}
5. Catch a specific exception first
The characteristic, known anomaly is captured first. Only the first catch statement that matches the exception in the catch block will be executed, so if you first find IllegalArgumentException, You will never get to the catch to handle more specific numberformatexception, because it is a subclass of IllegalArgumentException. so to first catch a particular exception class and add some catch statements at the end that handle not very specific exceptions. subclasses should be in front, parent class behind. The last catch can write exception.
Public void Catchmostspecificexceptionfirst () { try { dosomething ("A message"); Catch (NumberFormatException e) { log.error (e); Catch (IllegalArgumentException e) { log.error (e) catch(Exception) { // use exception to capture indeterminate, ambiguous anomalies Log.error (e); }}
6. Do not use throwable in catch
because all exception (including error) are subclasses of throwtable. Error is a JVM exception that we cannot anticipate and modify. Throwable is not careful enough.
Public void donotcatchthrowable () { try { // do something Catch (Throwable t) { // don ' t do this! }}
7. Do not catch and throw exceptions
This may seem nice, when it happens, record an exception, and then re-throw it so that the caller can handle it appropriately. However, this will print both log information and exception information.
If you need to add additional information, you should catch the exception and wrap it in a custom message. But be sure to follow the 8th exception chain below.
Try { new Long ("xyz"catch (NumberFormatException e) { log.error (e); throw e;}
17:44:28,945 ERROR testexceptionhandling:65-java.lang.numberformatexception:for Input string: "xyz""main" Java.lang.NumberFormatException:For input string: "xyz" atjava.lang.NumberFormatException.forInputString ( Numberformatexception.java:+) at Java.lang.Long.parseLong (Long.java:589) at Java.lang.Long. (Long.java:965) at Com.stackify.example.TestExceptionHandling.logAndThrowException ( Testexceptionhandling.java:+) at Com.stackify.example.TestExceptionHandling.main ( Testexceptionhandling.java:58)
This may not be very clear, for example, if main invokes the B function, calls a function in B, an exception occurs in a, and we give the exception to the caller (main); This should be: Throw an exception in a, b chain throw, capture in main and process, record.
Public Static voidMain (string[] args) {System.out.println ("Please enter 2 Addend"); intresult; Try{result=Add (); System.out.println ("Result:" +result); } Catch(Exception e) {//1. RecordLog.error (e); //2, processing, such as printing;E.printstacktrace (); }}//gets the input 2 integers returnedPrivate StaticList<integer>getinputnumbers () {List<Integer> nums =NewArraylist<>(); Scanner Scan=NewScanner (system.in); Try { intNUM1 =Scan.nextint (); intnum2 =Scan.nextint (); Nums.add (NewInteger (NUM1)); Nums.add (NewInteger (num2)); }Catch(inputmismatchexception immexp) {ThrowImmexp; }finally{scan.close (); } returnnums;}//Perform an addition calculationPrivate Static intAdd ()throwsexception{intresult; Try{List<Integer> nums =getinputnumbers (); Result= Nums.get (0) + nums.get (1); }Catch(inputmismatchexception immexp) {Throw NewException ("Calculation failed", IMMEXP);/////////////////////////////Chaining: Constructs a new exception object as a parameter for an exception object. } returnresult;}
8, chain--packaging anomalies
the chain of exceptions can concatenate the exceptions of multiple modules so that the exception information is not lost.
Exception Chaining: Constructs a new exception object as a parameter to an exception object. The new heterogeneous object will contain information about the previous exception. This technique is mainly implemented by a function with Throwable parameters for the exception class. As an exception to this argument, we call him the root cause anomaly (cause).
Public Static voidMain (string[] args) {System.out.println ("Please enter 2 Addend"); intresult; Try{result=Add (); System.out.println ("Result:" +result); } Catch(Exception e) {e.printstacktrace (); }}//gets the input 2 integers returnedPrivate StaticList<integer>getinputnumbers () {List<Integer> nums =NewArraylist<>(); Scanner Scan=NewScanner (system.in); Try { intNUM1 =Scan.nextint (); intnum2 =Scan.nextint (); Nums.add (NewInteger (NUM1)); Nums.add (NewInteger (num2)); }Catch(inputmismatchexception immexp) {ThrowImmexp; }finally{scan.close (); } returnnums;}//Perform an addition calculationPrivate Static intAdd ()throwsexception{intresult; Try{List<Integer> nums =getinputnumbers (); Result= Nums.get (0) + nums.get (1); }Catch(inputmismatchexception immexp) {Throw NewException ("Calculation failed", IMMEXP);/////////////////////////////Chaining: Constructs a new exception object as a parameter for an exception object. } returnresult;}/*Please enter 2 addend r 1java.lang.exception: Calculation failed at practise. Exceptiontest.add (exceptiontest.java:53) at practise. Exceptiontest.main (exceptiontest.java:18) caused by:java.util.InputMismatchException at Java.util.Scanner.throwFor (scanner.java:864) at Java.util.Scanner.next (scanner.java:1485) at Java.util.Scanner.nextInt (scanner.java:2117) A T Java.util.Scanner.nextInt (scanner.java:2076) at practise. Exceptiontest.getinputnumbers (exceptiontest.java:30) at practise. Exceptiontest.add (exceptiontest.java:48) ... 1 More*/
Additional: The details of the finally block
- Do not use return in fianlly.
- Do not throw an exception in finally.
- To lighten the finally task and not to do something else in finally, the finally block is the most appropriate way to release resources.
- Will try to write all of the return to the last side of the function instead of the try ... catch ... finally.
Java Exception Practical matters