Java-exception details, java-Details

Source: Internet
Author: User

Java-exception details, java-Details

(1) Causes of exceptions

Exception Handling can improve program robustness. The C language uses function return values to handle exceptions. disadvantages of this approach:

1. The returned value may conflict with the existing logic.

2. Poor code readability. The Execution Code is mixed with the exception handling code.

3. You need to know the function return value details for processing.

/*** Exception Handling demo *** @ author peter_wang * @ create-time 9:24:35 */public class ExceptionDemo {/*** @ param args */public static void main (string [] args) {int num = operateNum (5); // The external user of the function needs to know the exception return value. // The function calculation result is-1, essentially not within the exception scope // Exception Handling increases program coupling, and Exception Handling and normal processing are obfuscated together if (num =-1) {System. out. println ("incorrect input parameter");} else {System. out. println ("Calculation Result:" + num) ;}} private static int operateNum (int num) {if (num = 0) {return-1 ;} num = 10/num; num-= 3; return num ;}}


(2) exception Classification


System-level error (error): If the memory is used up, ignore it.

Compile-time error: this exception must be wrapped in the capture statement displayed in the Code; otherwise, it cannot be compiled, such as FileNotFoundException.

Runtime error: an error occurs when the code is not standardized. If an error occurs, the programmer must modify the bug, such as null pointer exception and array subscript out-of-bounds.


(3) abnormal use

1. Do not ignore exceptions

        try {           ......        }        catch (Exception e) {        }
The failure to handle exceptions violates the original intention of the exception design, and it is difficult to find the cause of the error because of program errors.

2. Do not separate the logic code.

FileInputStream is = null;        try {            is = new FileInputStream(new File(""));        }        catch (FileNotFoundException e) {            e.printStackTrace();        }        try {            is.read();        }        catch (IOException e) {            e.printStackTrace();        }
Exception capture separates the Code with strong logic, making it less readable. Use the following code:

FileInputStream is = null;        try {            is = new FileInputStream(new File(""));            is.read();        }        catch (FileNotFoundException e) {            e.printStackTrace();        }        catch (IOException e) {            e.printStackTrace();        }
3. exceptions that can be handled are not passed up

There are two ways to handle exceptions: catch and throw.

Transferring Up indicates that too many unknown items can be processed by yourself, unless you know that the information needs to be processed by the upper layer in advance.

4. IO Exception Handling

If you use resources such as database connections or network connections, remember to clean up the resources in finally (such as closing the database connection or network connection ).

5. Do not use Exception to catch exceptions.

Exception types are refined to facilitate handling and error information capturing.




Java Exception Handling

Exception Handling is a very important aspect in programming and a major difficulty in programming. From C, you may already know how to use if... else... to control exceptions, it may be spontaneous. However, this kind of control exception is painful. If the same exception or error occurs in multiple places, you must perform the same processing in each place, it's quite troublesome! At the beginning of its design, the Java language considered these issues and proposed a framework scheme for exception handling. All exceptions can be represented by one type, different types of exceptions correspond to different sub-class exceptions (here the exception includes the error concept), defines the exception handling specifications, and adds the exception chain mechanism after version 1.4 to facilitate exception tracking! This is the skill of the Java language designer and also a difficult point in the Java language. The following is a summary of my knowledge about Java exceptions, which is also a collection of resources.
I. Basic knowledge about Java exceptions
Exceptions are some errors in the program, but not all errors are exceptions, and sometimes they can be avoided. For example, if your code is missing a semicolon, the running result indicates that the error occurs in java. lang. error; if you use System. out. println (11/0), so you do the divisor with 0, will throw java. lang. arithmeticException. Some exceptions need to be processed, while others do not need to be captured and processed. The sky is unpredictable, and everyone is lucky, as are Java program code. In the programming process, we should first avoid errors and exceptions as much as possible. For unavoidable and unpredictable situations, we should consider how to handle exceptions. Exceptions in Java are represented by objects. Java processes exceptions by exception type. Different exceptions are classified by type. Each exception corresponds to a class, and each exception corresponds to an exception (class) object. Where does the exception class come from? There are two sources: one is some basic Exception types defined by the Java language itself, and the other is exceptions defined by the user by inheriting the Exception class or its subclass. The Exception class and its subclass are a form of Throwable, which specifies the conditions that a reasonable application wants to capture. Where can an exception object come from? There are two sources: one is that the Java Runtime Environment automatically throws the exception generated by the system, regardless of whether you are willing to capture and process it, it will always be thrown! For example, an exception occurs when the divisor is 0. The second is an exception thrown by the programmer. This exception can be defined by the programmer or defined in the Java language. An exception is thrown using the throw keyword, this exception is often used to report abnormal information to the caller. Exceptions are for methods. Throws, declaration throws, captures, and handles exceptions in methods. Java exception handling is managed by five keywords: try, catch, throw, throws, and finally. The basic process is to use the try statement block to wrap the statement to be monitored. If an exception occurs in the try statement block, the exception will be thrown, your code can capture and handle this exception in the catch statement block, and some system-generated exceptions are automatically thrown during Java runtime. You can also declare the method to throw an exception through the throws keyword, and then throw an exception object through throw in the method. The finally statement block is executed before the return method is executed. The general structure is as follows: try {program code} catch (variable name 1 of exception type 1) {program code} catch (exception type 2 abnormal variable name 2) {program code} finally {program code} catch statements can have multiple to match multiple exceptions, after one of the above matches, only the matching exception is executed when the catch statement block is executed. The catch type is defined in the Java language or defined by the programmer. It indicates the type of the Code that throws an exception, and the variable name of the exception indicates the reference of the object that throws the exception, if catch captures and matches the exception, you can directly use the exception variable name. At this time, the exception variable name points to the matched exception and can be referenced directly in the catch code block. This is not... the remaining full text>
 
How does java handle exceptions?

When there is an external environment problem that cannot be controlled by the program (the file provided by the user does not exist, the file content is damaged, and the network is unavailable...), JAVA will describe it with an exception object.
JAVA uses two methods to handle exceptions:
1. handle exceptions directly;
2. Send the exception to the caller for processing.
JAVA exceptions can be divided into three types:
(1) Check Exception: java. lang. Exception
(2) runtime exception: java. lang. RuntimeException
(3) Error: java. lang. Error
The top layer is the java. lang. Throwable class. Check exceptions, runtime exceptions, and errors are all child classes of this class.
Java. lang. Exception and java. lang. Error are inherited from java. lang. Throwable, while java. lang. RuntimeException is inherited from java. lang. Exception.
Checksexual exception ------ the program is correct, but the cause is that the external environment conditions are not met. For example: user errors and I/O problems-the Program tries to open a remote Socket port that does not exist. This is not a logic error of the program itself, but probably a remote machine name error (User spelling error ). For commercial software systems, program developers must consider and handle this issue. The JAVA compiler enforces the processing of such exceptions. If such exceptions are not caught, the program cannot be compiled.
Runtime exception ------ this means that the program has bugs, such as array out-of-bounds, 0 is excluded, and the input parameter does not meet the specifications ..... this type of exception must be avoided by changing the program. The JAVA compiler requires that such exceptions be handled.
Error ------ it is generally rare and difficult to solve through a program. It may be due to program bugs, but it is generally due to environmental problems, such as memory depletion. Errors do not need to be handled in the program, but are handled in the runtime environment.
How to handle exceptions?
1. try... catch
When an exception occurs during the running of the program, the program will be interrupted from the occurrence of the exception and the exception information will be thrown out.
Java code
Int x = (int) (Math. random () * 5 );
Int y = (int) (Math. random () * 10 );
Int [] z = new int [5];
Try
{
System. out. println ("y/x =" + (y/x ));
System. out. println ("y =" + y + "z [y] =" + z [y]);
}
Catch (ArithmeticException exc1)
{
System. out. println ("Arithmetic Operation exception:" + exc1.getMessage ());
}
Catch (ArrayIndexOutOfBoundsException exc2)
{
System. out. println ("data out-of-bounds exception:" + exc2.getMessage ());
}
Note: Both ArithmeticException and ArrayIndexOutOfBoundsException are runtime exceptions: java. lang. runtimeException. If you do not need try... catch capture, the program can also be compiled, but if it is a checked exception: java. lang. exception, required and must use try... catch... process it.
2. finally
If you set the finally block to try... catch... after a statement, the finally block is generally executed, which is equivalent to 10 thousand of the security, even if the previous try block is different ...... remaining full text>

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.