Java program exception handling (Handout)

Source: Internet
Author: User
Tags finally block
For java program exception handling (Handout)-Linux general technology-Linux programming and kernel information, see the following for details. Lecture 16th: Exception Handling
16.1 introduction:
Exceptions are any errors or unexpected behaviors encountered during program execution.
Any of the following situations can cause exceptions: your code or called code (such as the shared library) has errors and the operating system resources are unavailable, unexpected situations (for example, codes cannot be verified) in the public Language Runtime Library, etc.

Exception Handling for C ++ about Exception Handling,
Adding a class to an object may contain some errors.
Java exception handling similar to C ++
1. There are many popular methods to handle errors
2. The general method is to distribute the program processing code segment to the system code and handle the error where an error may occur.
Advantage: it is easy for programmers to see the exception handling in the program in an organized manner.
Disadvantage: The exception handler is "messing up" the code. It is difficult for programmers to care about whether the program can complete the function normally, but only about the performance.
3. Common exception examples include: array subscript out of bounds, Algorithm Overflow (beyond the value expression range), zero division, invalid parameters, memory overflow
Exception Handling function: mainly handles some synchronization exceptions (with a division of 0). It is not suitable for handling asynchronous events (Disk I/O End, arrival of network information, Mouse clicking, and keyboard hitting) it is best to use java event listening.
Exception Handling program: a program that allows the system to recover from exceptions.
Exception Handling: exception handling programs are used when exception diagnosis and exception handling are not in the same position (if the user keeps talking with the program through the keyboard, then the handling keyboard input cannot be used)
Precautions for exceptions:
1. The exception handling location must be different from the exception location (if a program can handle its own errors, it adopts the traditional error handling method for local processing)
2. Avoid Exception Handling instead of error handling. If this happens, the program becomes clearer.
3. Although exception handling can be used instead of error handling, it will reduce the performance.
4. Exception Handling takes special execution time of the program
5. Exception Handling can improve program Fault Tolerance
6. programmers use the JAVA standard exception handling function to replace their dedicated methods and improve program clarity in large projects.
7. Exceptions are child classes inherited from super-class exceptions. They are mainly used to handle "uncaught exceptions" and unexpected exceptions.
8. Exception Handling in java:

Exception Handling is handled by the Method caller or Method caller,
9. Exception Handling applicable to component systems developed separately
10. Some programmers tend to delay or forget the compilation of the error handling program when they use programming languages that do not support exception handling. Therefore, Java forces programmers to start exception handling from the very beginning of the project, programmers must devote a lot of energy to integrating exception handling policies into software products.
11. The best way to design a system is to integrate Exception Handling into the system. If the system is implemented, it is difficult to add the exception handling function.

16.2 how to handle exceptions:

Use exception handling in the following situations:

1. When a method cannot implement its functions due to uncontrollable reasons;
2. Handle the overall exceptions from program components. These program components are not suitable for handling exceptions directly.
3. In large projects, errors are handled in the same way for each project.
4. Each exception in the class library requires a unique error handling. It is appropriate to use exception handling in the class library.

16.3 other error handling technology:

How to handle exceptions:
1. Exceptions can be ignored in programs (ignoring exceptions in large public software and critical processing software may cause major software damages, while some errors can usually be ignored in software used by the user)
2. In case of an exception, the program can terminate the operation as prompted (but it is absolutely unavailable to handle the key tasks. <God 5 returns to the Warehouse Temperature Control System> 〉? 863 Project .)

16.4 java Exception Handling basics:

Java exception handling is applicable when a method can detect that the error ticket cannot handle the error, in this way, an exception will be thrown (JAVA cannot ensure that the "exist" exception handler can handle a certain exception. If "exist", "Catch" the exception and handle the "exception ", if not:

Command Line APP/console APP (not based on GUI). When exceptions cannot be "captured", the program runs the default exception handler and exits JAVA, if an Applet or GUI-based APP is not "captured", the GUI still displays the default exception handler while running, and the user's GUI is in an unstable state)
)
JAVA code: 1. Code with exceptions -----{...... Try {Throw an exception} ----- program block ...... Catch1 {exception handler 1 };...... Catch100 {exception handling program 100}; finally {programs executed if no exceptions occur}
1. If try throws an Exception, the App looks for the Exception ~ 100 find an appropriate exception handler. If found, run the CATCH {} code. If not, run the code after the last catch {}.
2. If try does not throw an Exception, execute the code after the last catch.

3. throws clause to throw a specified exception. The exception throw point (in the throws statement position, try {} program block, or try () program block directly or indirectly called)

4. java uses the termination method for exception handling, not the restoration method for Exception Handling

5. Information surrounding the exception when an exception occurs (the type of the thrown object itself) ----------- exception handler

12.5 a simple example of Exception Handling: the divisor is 0

Requirement: Use a small application to complete two-digit Division calculation

Analysis:
We use a top-down, progressive refinement method:
1. In the first step, we generally process the classes that we have completed exception handling in the program and complete the exception handling function. Because an exception may occur when the divisor is 0, we look for java. the Exception classes in the lang package find that ArithmeticException in the RuntimeException class set can handle operation exceptions, so we have a DivideByZeroException (inherited from ArithmeticException) special class to specifically handle the Exception with a division of zero. In DivideByZeroException (), call super () (specifically initialize the method for passing parameters) to pass the object description (initial state) after exception handling)
2. Step 1: Create an Applet class to complete two-digit Division calculation
3. Step 2: processing objects and Methods: declare four GUI Component Objects and one for storing the computing result (double) and two basic types of divisor and divisor (int)

A. initialize the object method init ()
B. Method for triggering event calculation (return judgment) after processing input on the divisor keyboard () action ()

A. In this method, there may be a possibility that the divisor is 0, and an error is returned only during calculation. If an error occurs, an exception must be handled, in this case, I use the try {} program block to call the method quotient to calculate result = quotient (number1, number2), 1, and then let quotient () method (throw exception program block using throws Ex {} in the method body --- this is a deep nesting) throw an exception (because the processing information is relatively simple, but there is information transfer, we have it be dragged for post-processing) we did not explicitly throw an exception in the try () block. If an exception is thrown, an exception is obtained. The catch {} block is used to complete the process. a) and the quotient () (the actual deep nested throws Ex {} throws the exception block ), when the DivideByZeroException is set to 0, a new catch {} "capture" (specify the matching type DivideByZeroException) quotient () is called to create a throw clause ), the exception message is received by the exception, and the toString () method is called to convert the exception to a string, using showStatus (exception. toString (); displayed (due to abnormal requirement ). B) if the divisor is used! If the value is 0, no exception is thrown. Then, the program is returned to the quotient () method call in the try () program block, and then showStatus () is used () display formula and result (number1 + "/" + number2 + "=" + Double. the toString (result) program will skip the catch {} block, and the action () method will execute return true

Note: When quotient () throws an exception message (DivideByZeroException), quotient () terminates the execution and marks all objects (4 + 2 + 1, it is used for useless unit recycling. Before useless unit recycling, the termination function of these objects will be run. If an exception is thrown, try to terminate before the program block executes showStatus. If an object is automatically created before try throws an exception, the object will be marked for useless unit recycling. At the same time, the termination function of these objects will be run before the collection.
B. In the action () method, pay attention to the processing: In TextField, after 2nd inputs are completed and press enter, how should the divisor obtain the input number (number1 = Integer. parseInt (input1.getText), how to obtain valid text (setText () in the text box ()). also include judgment (if (event.tar get = input2 ))

C. Because the quotient () method has many tasks, it is necessary to separate the method with the action to display the clarity and readability of the program, while improving the execution efficiency and stable performance.

Class Diagram and flowchart:

Code:
// Fig 16.4: DivideByZeroException. java
// W. Qiang
/// 2005. J.6
Public class DivideByZeroException extends ArithmeticException {
Public DivideByZeroException ()
{
Super ("Attempted to divide by zero ");
}
}
Import java. awt .*;
Import java. awt. event .*
Import java. applet. Applet;

Public class DivideByZeroTest extends Applet
{
Label prompt1, prompt2;
TextField input1, input2;
Int number1, number2;
Double result;

Public void init ()
{
Prompt1 = new Label ("input dividend ");
Input1 = new TextField (10 );
Prompt2 = new Label ("Enter the divisor and press ENTER ");
Input2 = new TextField (10 );
Add (prompt1 );
Add (input1 );
Add (prompt2 );
Add (input2 );
}

Public boolean action (Event event, Object obeject)
{
If (event.tar get = input2)
{
Number1 = Integer. parseInt (input1.getText ());
Input1.setText ("");
Number2 = Integer. parseInt (input2.getText ());
Input2.setText ("");

Try {
Result = quotient (number1, number2 );
ShowStatus (number1 + "/" + number2 + "=" + Double. toString (result ));
}

Catch (DivideByZeroException exception ){
ShowStatus (exception. toString ());
}
}
Return true;
}
Public double quotient (int numerator, int denominator) throws DivideByZeroException
{
If (denominator = 0)
Throw new DivideByZeroException ();
Else (denominator! = 0)
Return (double) numerator/denominator;
}
}

12.6 try block:
Try {
......}
Catch (){
.......}
Finally {......}
Try followed by 0 ~ Multiple catch Blocks
If try throws an Exception, the App looks ~ 100 find an appropriate exception handler. If found, run the CATCH {} code. If not, run the code after the last catch {}.
If try does not throw an Exception, execute the code after the last catch.
Finally {whether a program is executed in case of any exceptions in the category. The function call must be terminated after the resource is released to avoid resource leakage}
16.7 throw an exception:
The throw clause is used to throw an exception, while the throws clause is used to specify an exception.
The number of throw operations is all the derived classes of Throwable, and the direct subclass of Throwable is Exception (Exception, caused by caught problems, should be handled) and Error (major system problems, generally not captured)
Throw exception throw points include try {} blocks, try {} blocks, some deep nested scopes, and some deep nested methods of try {} blocks. throws specifies exceptions and throw exceptions.
Try {} does not include the error detection statement and throw clause, but the objects referenced in the program block will execute the error detection code in the constructor and throw an exception.
We only need to terminate the execution of blocks that generate exceptions without stopping the entire program.
Exception information is transmitted through object reference, and then the parameter name (Object Name) in the catch block is referenced
16.8 capture exceptions:

The exception handler is included in the catch Block.
Syntax:
Catch (classNmae --- specifies the type of exception to be thrown, parameter name ----- used to reference the object captured by the processing program) {javaCode ----- executable code for exception handling}

Catch usage considerations:
1. If the program control returns the first statement after throw after Exception Processing, it will cause a logic error.
2. You cannot set multiple catch Block parameters. One catch has only one parameter.
3. If both catch blocks (both related to a try block) are used to catch exceptions of the same type, a syntax error will occur.
4. Special exceptions may not be found and need to be found in the next try. If not, the command line APP/console APP (not based on the GUI) will exit the program, the Applet or GUI-based APP will continue to execute an APP in an unstable state.
5. If a certain type of exception occurs, several exception handlers may match him or her, execute the first-matching exception handler.
6. A program can handle many closely related exceptions at the same time. The ExceptionGroup provides an exception class and a catch handler. When an exception occurs, you can create an exception object based on the data of different instances and check the data by catch to determine the exception type. We generally do not advocate this programming style, so it is best to use an inherited method to solve the problem.
7. In the exception handling program, you cannot access the objects defined in the try block. Exception Handling starts and try ends.
8. If an exception is thrown when an exception handler is executed and the original try block has been terminated, let the original try outer try handler handle the exception, at the same time, the outer try program monitors and processes the catch handler errors of the original try block.
9. Exception Handling program form: A. Re-throw an exception; B. Convert the exception type by throwing another exception of different types; c. After the last exception handling program is executed, complete any necessary recovery and continue the program execution. D. determine the cause of the error and handle it, and re-call method E that previously generated this exception, simply return a status value to Runtime ............... And so on.
10. The traditional control flow does not use exceptions. "extra" exceptions will "mask" the real error types and it is difficult for programmers to track those large numbers of exceptions, besides, exceptions are not common.
11. When a catch handler throws an exception, it will be handled by the catch handler or another handler related to the same try block, and a logical error will occur.

16.9 throw an exception:
If an exception occurs in the catch exception handler, other catch handlers are required to handle the exception.
Throw can be used to throw an exception.

16.10 throws clause:

Purpose: list the exceptions that can be thrown by a method.
Int g (float h) throws a, B, c
{
// Method body
}
The thrown object is a specified class object or subclass object.

1. runtime exception: exceptions are inevitable.
This exception is derived from the RuntimeException class.
Including: ArrayIndexOutOfBoundsException (accessing an out-of-bounds array subscript), NullPointerException (Null reference operation throws --- declaration without creating an object );
ClassCastException (caused by invalid type conversion)
IOException, InterruptedException

Throws does not need to explicitly point out RuntimeException and Error, but must point out that the method or method called by this method explicitly Throws a non-RuntimeException
3. java Exception differentiation: checked Exception (non-RuntimeException); unchecked Exception (RuntimeException); Error

Note:
1. method throws a checked Exception. If the Exception is not listed in the throws clause, a syntax error occurs.
2. If you try to throw an exception in a method without a throws clause, a syntax error will occur.
3. If method1 calls method2 (display throws the checked Exception), the Exception must be listed in the method1 clause, unless method2 has caught this Exception
4. The throws list of the subclass method is a subset of the throws list of the parent method.
5. Capture exceptions must be handled to meet the requirements of "java capture or Declaration ".
6. the java compiler forces programmers to handle exceptions and never ignores exception handling.
7. For errors listed in java, see java. lang package errors (AWTError) of j2SDK 1.42 encryption ention)
8. For exceptions listed in java, see java. lang package Exception, java. util package Exception, java. io package Exception, java. awt package Exception, and java.net package Exception of j2SDK 1.42 conflict ention.

16.11 constructor, termination function, and Exception Handling

When the constructor detects an error (return value is not allowed) solution (let the program know that the object cannot be correctly constructed ):
1. This error object is returned directly. When this object is used for judgment, it is used to determine whether the object is incorrect.
2. setting a global variable outside the constructor is not a good method. 3. Throw an exception, pass the sub-function error information to the outside, and handle the error.
4. When the function throws an Exception, the object created by the function will be marked and recycled with the final useless unit. Therefore, you need to call the termination function.

16.12 exceptions and inheritance:

Due to the inheritance relationship, various errors can be processed with polymorphism.
Generally, it is best to capture and handle parent class exceptions (only when the processing methods of all subclass objects are consistent). Otherwise, capture subclass exceptions

16.13 finally block

If the program shows that some resources are used, the release of resources must be completed at the end, that is, the useless unit recycling. In C and C ++, it is common that pointers cannot be recycled and functions cannot be terminated, memory leakage"
Java automatically recycles units to avoid memory leaks. However, java also has other "resource leaks"
Some resource release code is usually used in finally blocks.
1. finally block: Close all open files in the try Block
2. java does not completely eliminate resource leaks. When an object does not exist, java recycles the object as a non-yong unit. When a programmer mistakenly references an object, memory leakage occurs.
3. exception (String informationString): informationString describes this type of exception, and getMessage is used to obtain the information (used to return the description String stored in an exception ). PrintStackTrace (used to print the content of the method call stack, which is particularly useful to the test program ).
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.