Exception handling in Java from concept to instance

Source: Internet
Author: User

1. Concept
Adopt a new exception handling mechanism
In the previous process of program development, the return value is often used for processing. For example, when you write a method, you can return a status code that the caller determines whether it is an error based on the status code. If the status code represents an error, call this to do the appropriate processing, or display an error page or error message. The method of processing by the return value is valid, but there are many deficiencies in it.
  
1. Complicated procedure
  
2. Poor reliability
  
3. Limited return information
  
4, Return code standardization difficulties
  
The advantages of combining error codes and exception handling are as follows:
  
1. Separate the error code from the regular code
  
2. You can propagate error messages in catch
  
3. You can group the error types
  
4, convenient positioning errors, maintenance
  
Abnormal
An exception is an exception event, which is the event that the program fires when it encounters an abnormal condition. Many exceptions, such as program errors, null pointers, array overflows, and so on. Here is an error flow
  
First step: Insert the user's keynet, log in the system
  
The second step: the server verifies the user's identity, determines the user's permissions
  
Step three: Return the wrong information.
  
This is a simple exception handling example, how simple, convenient, quick to get error messages. Can be handled in a combination of error codes and exceptions.
  
   2. Exception Handling
Java exceptions are object-oriented. A Java exception is an object that describes an exception. When an exception occurs, a exception object is created and placed in the exception's member function.
  
Java exception handling is achieved through 5 key words: Try,catch,throw,throws and finally. The error handling structure in the Java language consists of three blocks of try,catch,finally. Where the try block holds the Java language in which the exception may occur, and governs the associated exception pointer, the catch block is immediately behind the try block, which is used to fire the caught exception, and the finally block contains the resources, handles, and so on, that the cleanup program did not release. The finally block is executed regardless of how the code in the try block exits.
  
Try ... catch ... Block
You can use try to specify a piece of program that prevents all exceptions. Immediately following the TRY program block, you should include a
  
or more catch clauses to specify the type of exception you want to catch: The format of the try catch is generally:
  
try{
  
/**do something*/
  
}catch (...) {
  
...
  
}catch (...) {
  
...
  
}
  
For example:
  
try{
  
int a= 100/0
  
}catch (Exception e) {
  
System.out.PRintln (E.getmessage ());
  
}
  
Whenever a Java program fires an exception, it actually fires an object, and only the object whose superclass is the Throwable class can be fired. Some methods are available in the Throwable class. For example, the GetMessage () method prints out the exception corresponding information.
  
The goal of the catch clause is to resolve the exception, set the variable to a reasonable state, and continue running as if there were no errors. If a subroutine does not handle a single exception, it is returned to the previous level of processing, so that it can continue recursively up to the outer level.
  
Finally block
The finally key word is the best complement to the Java exception handling model. The finally structure makes the code always executes, regardless of whether or not an exception occurs. Use finally to maintain the internal state of an object and to clean up non-memory resources. If you don't have a finally, your code will be confusing. For example, the following code illustrates how you must write code to free non-memory resources without using finally:
  
Import java.net.*;
Import java.io.*;
Class withoutfinally
{
public void Foo () throws IOException
{
Create a socket on any of the free ports
ServerSocket ss = new ServerSocket (0);
try {
Socket socket = ss.accept ();
The other code here ...
}
catch (IOException e) {
Ss.close (); 1
Throw e;
}

//...
Ss.close (); 2
}
}
This code creates a socket and calls the Accept method. You must close this socket before exiting the method to avoid resource vulnerabilities. To complete this task, we call close at//2, which is the last statement of the method. But what if an exception occurs in the try block? In this case, the close call at//2 never occurs. Therefore, you must catch this exception and insert another call to close at//1 before you re-emit the exception. This will ensure that the socket is closed before exiting the method.
  
It is cumbersome and error-prone to write code, but it is essential in the absence of a finally. Unfortunately, in languages that do not have a finally mechanism, programmers may forget to organize their code in this way, leading to resource vulnerabilities. The finally clause in Java solves this problem. With finally, the preceding code can be rewritten in the following form:
  
Import java.net.*;
Import java.io.*;

Class withfinally
{
public void Foo2 () throws IOException
{
Create a socket on any of the free ports
ServerSocket ss = new ServerSocket (0);
try {
Socket socket = ss.accept ();
The other code here ...
}
finally {
Ss.close ();
}
}
}
The finally block ensures that the Close method is always executed, regardless of whether an exception is emitted within the try block. Therefore, you can ensure that the Close method is always called before exiting the method. This allows you to be confident that the socket is closed and that you are not leaking resources. There is no need for another catch block in this method. The catch block is provided in the first example just to close the socket, which is now closed by finally. If you do provide a catch block, the code in the finally block executes after the catch block finishes.
  
The finally block must be used in conjunction with a try or Try/catch block. In addition, it is not possible to exit the try block without executing its finally block. If the finally block exists, it is always executed. (from that point of view, the statement is correct.) There is a way to exit a try block without executing a finally block. If the code executes a system.exit (0) inside the try; Statement, the application terminates without performing a finally execution. On the other hand, if you unplug the power during the try block execution, finally will not execute. )
  
Try...catch...finally Block
It is best to use this structure to handle exceptions. Catch exceptions in catch and eliminate unnecessary resources in the finally block, so that the program structure will be more complete and robust. For example:
  
try{
  
/**to do */
  
}
  
catch (Exception ex) {
  
System.out.println (Ex.getmessage ());
  
}
  
finally{
  
Clearupall ()
  
}
  
   3. Excitation anomaly
The Java language can not be snapped directly in the method, and throws the exception to the upper-level caller with the throw statement. The throw statement is to explicitly throw an exception; First you must get a Throwable instance handle, pass the parameter to the catch, or create one with the new operator.
  
Format: throw new Whcaexception (e.getmessage);
  
The program terminates immediately after the throw statement, and the statements following it are not executed, and then in all the try blocks that contain it, look for the catch that contains it.
  
Declaring exception classes
When the throw statement is used in the method description, throw has a useful throws instead. The key word throws is used to indicate the various exceptions that a method may throw. For most exception subclasses, the Java compiler forces you to declare the type of exception thrown in a method. As follows:
  
Format: Type Method_name (arg_list) throws whcaexception{
  
......
}
  
For example: public void execute (String str,int index) throws whcaexception{
  
try{
  
}
  
catch (Exception e) {
  
throw new Whcaexception ("Jb:m:" +e.getmessage);
  
}
  
}
  
   4. Create your own exception class
When programmers use Java classes to provide specific functionality, it is often necessary to ensure a good relationship between classes, and the interface between classes is easy to understand and implement, which is to define a new exception class. It is recommended to create your own exception classes for ease of maintenance and governance.
  
To define a new exception class
Exception is typically used as a superclass of the exception class, such as:
  
Package Whca.common;
  
public class Whcaexception extends exception{
  
Public Whcaexception () {
  
}
  
Public Whcaexception (String s) {
  
Super (s);
  
}
  
}
  
   5. Example
The following is an example: Testservlet calls TestDB and Testpsi, (with code) what happens when an exception occurs the fastest solution to an exception error.
  
During the entire project development process, specify the error code table and categorize it. such as the PSI class, database exception class code, the application of Exception class code, XML exceptions, network communication anomalies and so on;
  
Using your own exception class, when encountering an exception, the exception that is fired carries the path of the wrong class or exception method:
  
such as: Setflag ("PSI001");
  
throw new Whcaexception ("Jb:testa m:exe1" +e.getmessage);
  
Here: PSI001 is the error code, "Jb:testa m:exe1" is the exception chain, E.getmessage is the exception information.
  
For example: The list of error messages encountered is: Jb:testb m:exe2 jb:testa m:exe1 java.sql.

Exception handling in Java from concept to instance

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.