Java exception handling techniques and principles summary

Source: Internet
Author: User
Tags exception handling getmessage throwable try catch

Java exception handling involves the program flow of the jump, so the virtual machine needs to save the program's execution process, so that the exception occurs when the correct jump, which also causes the use of exceptions will incur additional overhead, so be careful to use the exception.
There are several principles for using exceptions:
1, as far as possible to avoid the use of exceptions, the anomaly detected in advance.
2, do not set try and catch for each statement that may appear to be an exception.
3. Avoid throwing (throw) or catching (catch) runtime exception runtimeexception and error in the method.
4, avoid always catch exception or throwable, but to catch the specific exception class. This will make the program clearer.
5, do not suppress, conceal the anomaly. Throw out exceptions that cannot be handled, rather than handle them as they are captured.
6, do not use Try...catch in the loop, try to put the try...catch outside the loop or avoid use.
7, in the catch exception not as long as handling exceptions, and sometimes to the stack, some of the previous variables to deal with, or may appear a bug
Demo Example

Package book.exception;

Import Java.util.Date;
Import java.util.EmptyStackException;
Import Java.util.Stack;

/** *//**
* A few notes on using exceptions
* @author Joe
*
*/

public class exceptiontips ... {

public static void Main (string[] args) ... {

(1) As far as possible to avoid the use of exceptions, the anomaly detected in advance
stack<object> stack = new stack ();
Try ... {
Stack.pop ();
catch (Emptystackexception e) ... {
//....
}
You should use the following method to avoid using exceptions
if (!stack.isempty ()) ... {
Stack.pop ();
}

(2) Do not set try and catch for each statement that may appear
Try ... {
Stack.pop ();
catch (Emptystackexception e) ... {
//....
}
String data = "123";
Try ... {
Double.parsedouble (data);
catch (NumberFormatException e) ... {
//....
}
You should use the following method to place two statements in a try block
Try ... {
Stack.pop ();
Double.parsedouble (data);
catch (Emptystackexception e) ... {
//....
catch (NumberFormatException e) ... {
//....
}

(3) Avoid throwing or capturing Run-time exception runtimeexception and error in the method.
such as memory errors, etc.
Avoid any of the following situations
String[] Array;
Try ... {
Array = new string[1000];
Array = new string[1000000]; OutOfMemoryError exception appears
catch (OutOfMemoryError e) ... {
Throw e;
}
Use the following code directly
Array = new string[1000];

(4) Avoid always catch exception or throwable, but to catch specific exceptions
This can be done according to different exceptions to do different processing, so that the program clearer
Try ... {
Stack.pop ();
Double.parsedouble (data);
catch (Exception e) ... {
Catch Exception should be avoided!!!
}

(5) Do not suppress or conceal anomalies. Throw out exceptions that cannot be handled, rather than handle them after they are captured
Try ... {
Double.parsedouble (data);
catch (NumberFormatException e) ... {
//.....
Throw e; Throw unhandled exceptions instead of concealing
}

(6) Do not use Try catch in a loop, try to put a try catch outside the loop or avoid using a try Catch
The following example takes more time to use try and catch in a loop, although there is no exception
int i = 0;
int ntry = 1000000;
Stack s = new stack ();
Long S1;
Long S2;
SYSTEM.OUT.PRINTLN ("Testing for empty stack");
S1 = new Date (). GetTime ();
for (i = 0; I <= ntry; i++) ... {
if (!s.empty ()) ... {
S.pop ();
}
}
S2 = new Date (). GetTime ();
System.out.println ((S2-S1) + "milliseconds");

System.out.println ("Catching Emptystackexception");
S1 = new Date (). GetTime ();
for (i = 0; i<=ntry; i++) ... {
Try ... {
S.pop ();
catch (Emptystackexception e) ... {
}
}
S2 = new Date (). GetTime ();
System.out.println ((S2-S1) + "milliseconds");
}

}
Program output:


Testing for empty stack
63milliseconds
Catching emptystackexception
1922milliseconds

I have made such mistakes before, and have seen many people writing this way. Let me also give an example:


public void WriteFile (File f) {
String content = null;
try {
Byte[] B = new byte[1024];
FileInputStream in = new FileInputStream (f);
In.read (b);
Content = new String (b);
catch (Exception e) {
System.out.println (E.getmessage ());
}

if (Content.indexof ("Hello") >-1) {
SYSTEM.OUT.PRINTLN ("yes");
} else {
System.out.println ("no");
}
}


The above is a simple way to have a hidden bug in the code. I encountered similar code when I was maintaining a system, in fact, a similar bug was hidden
The deeper. In cases where the system business and code are not very familiar, I recommend the following:


  public void WriteFile (File f) {
   String content = null;
   try {
    byte[] b = new byte[1024];
    FileInputStream in = new FileInputStream (f);
    In.read (b);
    content = new String (b);
  } catch (Exception e) {
    content= "";
  //If an exception occurs, the content may be empty
  //The nullpointerexception exception may occur when the content is being manipulated
   System.out.println (E.getmessage ());
 }
 //The following operation may occur NullPointerException exception
  if (content.indexof ("Hello") >-1) {
   SYSTEM.OUT.PRINTLN ("yes");
 } else {
   System.out.println ("no");
 }
 }
 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.