Java Certification Course 07

zhaozj2021-02-16  127

Chapter 7

This module tells the error handling device established in the Java programming language.

Section 1 related issues

Discussion - The following issues are related to the materials in this module:

- How to solve the runtime error in most programming languages?

Second source

After this module is completed, you can:

- definition exception

- Use TRY, CATCH and FINALLY statements

- Describe an exception classification

- Development procedure to deal with yourself

Third section

Distant

Milky error encountered by the exception class definition program

An exception occurs when the following conditions have occurred:

I want to open the file does not exist.

Network connection interrupt

The number of controlled operands exceeds a predetermined range

Very interested in being loaded

Error class defines a serious error condition

7.3.1 Introduction

What is an abnormal? In a Java programming language, a slight error condition that may encounter in an exception class definition program. You can write code to handle an exception and continue the program, not the program is interrupted.

In the program execution, any abnormal condition of the normal process process is incorrect or an exception. For example, an exception occurs when the following conditions occur:

- I want to open the file does not exist

- Network connection interrupt

- The number of controlled operands beyond the scheduled range

- I am very interested in being lost.

In the Java programming language, the error class definition is considered a severe error condition that cannot be recovered. In most cases, when such an error is encountered, it is recommended to interrupt the program.

Java programming language implements C anomalies to help build elastic code. When an error occurs in a program, the method of discovering an error can throw an exception to its calling program, which issues a signal that has occurred. Then, the call method captures the abnormality that is thrown, and then recovered again. This scheme gives the programmer a selection of write handler to handle exceptions.

By browsing the API, what kind of exception can be decided to throw.

7.3.2 instance

Consider the simple extension of the HelloWorld.java program version, it is loop through information:

Public class helloworld {

2. Public static void main (String args []) {

3. INT i = 0;

4.

5. String Greetings [] = {

6. "Hello World!",

7. "NO, I mean it!",

8. "Hello World !!"

9. };

10.

11. While (i <4) {

12. System.out.println (Greetings [i]);

13. i ;

14.}

15.}

16.}

Normally, when an exception is thrown, after its loop is executed four times, the program terminates, and has an error message, as the program as shown in front.

1. C: / student /> java helloworld

2. Hello World!

3. NO, I mean it!

4. Hello World !!

5. java.lang.ArrayIndexOutofboundsexception: 3

6. At HelloWorld.main (HelloWorld.java: 12) Exception Processing Allows the program to capture an exception, process them, and then proceeds to execute. It is a hierarchical chance, so the error does not intervene in the normal process of the program. Special circumstances occurs, is processed in the code block separated from the normal execution. This produces a more easy to identify and manage code.

Section 4 abnormal treatment

The Java programming language provides a mechanism to consider which exception is thrown and how to restore its mechanism.

7.4.1 TRY and CATCH statements

TRY and CATCH statements

TRY {

2. // Code That Might Throw a Particular Exception

3.} catch (myExceptionType E) {

4. // Code to Execute if a myExceptionType Exception is thrown

5.} Catch (Exception E) {

6. // Code to Excecute if a general exception Exception is thrown

7.}

To handle special exceptions, you will be able to throw an exception's code in the TRY block, then create a list of corresponding CATCH blocks, each can be thrown out of an exception. If the generated exception matches the match mentioned in Catch, the block statement of the CATCH condition is executed. After the TRY block, there may be many CATCH blocks, each handling different exceptions.

TRY {

2. // Code That Might Throw a Particular Exception

3.} catch (myExceptionType E) {

4. // Code to Execute if a myExceptionType Exception is thrown

5.} Catch (Exception E) {

6. // Code to Excecute if a general exception Exception is thrown

7.}

7.4.2 call stack mechanism

If one of the methods in the method throws an exception that is not processed in the corresponding TRY / CATCH block, then this exception is thrown into the callout method. If the exception has not been processed in the call method, it is thrown into the calling program of the method. This process has to continue until the abnormality is processed. If the abnormality has not been processed, it returns to main (), and even if main () does not process it, the exception is abnormally interrupt.

Consider such a situation, in this case, the main () method calls another method (for example, first ()), then it calls another (for example, second ()). If an exception occurs in Second (), you must do a check to see if the exception has a catch; if not, then check the next method in the call ()), then check the next (main ()). If this exception is handled in the call stack, a runtime error will occur, and the program terminates execution.

7.4.3 Finally statement

Finally statement

TRY {

2. Startfaucet ();

3. Waterlawn ();

4.}

5. finally {

6. stopfaucet ();

7.}

The Finally statement defines a single code block that is always executed without considering whether the abnormality is captured. The following sample code from the White Paper of Frank Yellin Frank Ye Lin, "Low-level safety in Java": 1. Try {

2. Startfaucet ();

3. Waterlawn ();

4.}

5. finally {

6. stopfaucet ();

7.}

In the previous example, the switch can be turned off even when the switch is turned on or watered on the grass. The code in the brackets behind TRY is called the protection code.

If the system.exit () method of the termination program is executed within the protection code, this is the only situation where the finally statement is not performed. This suggests that the control process can deviate from the normal execution order, for example, if a Return statement is embedded in the code within the TRY block, then the code in the Finally block should be executed before returnit.

7.4.4 Removing an exception

The following example is the rewrite of the main () method on page 169. The exception generated in the previous version of this program was captured, and the array index was reset so that the following procedures continued to run.

PUBLIC Static void main (string args []) {

2. INT i = 0;

3. String greetings [] = {

4. "Hello World!",

5. "NO, I mean it!",

6. "Hello World !!"

7.}

8. While (i <4) {

9. TRY {

10. System.out.println (Greetings [i]);

11.} catch (arrayindexoutofboundsexception e) {

12. System.out.Println ("Re-setting index value");

13. i = -1;

FINALLY {

15. System.out.Println ("this is alwaysprinted");

16.}

17. i ;

18.} // end while ()

19.} // end main ()

When the loop is executed, the information appearing on the screen will change.

Hello World!

2. this is alwaysprinted

3. NO, I mean it!

4. this is alwaysprinted

5. Hello World !!

6. this is alwaysprinted

7. RE-SETTINDEX VALUE

8. this is alwaysprinted

Section 5 exception classification

In Java programming languages, there are three categories. Java.lang.Throwable class acts as the parent class of all objects, you can use an exception handling mechanism to throw and capture these objects. Define methods in the Throwable class to retrieve error messages related to exceptions and print the stack tracking information that shows an exception. It has two basic subclasses of error and exception, as shown below:

The Throwable class cannot be used, and one of the subclass exceptions describe any special exception. The purpose of each abnormality is described below: - Error means a serious problem that recovery is not impossible but difficult but difficult. For example, memory is overflow. It is impossible to expect the program to handle this situation.

- RuntimeException represents a design or implementation problem. That is, it means that if the program runs normally, it will never occur. For example, if the array index expansion does not exceed the array boundary, then ArrayIndexOutofBoundSexception is not thrown. For example, this is also applicable to uncounting an null value object variable. Because a correct design and implementation procedure never doing this abnormality, it usually does not do it. This will lead to a runtime information, you should ensure that the measures can be made, not where it is hidden, no one is not paying attention.

- Other abnormalities indicate a difficulty of running, which is usually caused by environmental effects and can be processed. Examples include files not found or invalid URL exception (the user has a wrong URL), if the user misunderstands, both are easy to appear. Both of these may appear because the user is wrong, which encourages the programmer to deal with them.

Section 6 Common Unusual

Unusual

- ArithMeticexception

- NullPointersRexception

- NegativeArraysizeException

- ArrayIndexOutofboundSexception

- SecurityException

The Java programming language provides several predefined exceptions. Below is a few more common in common unusual:

- ArithmeticException - the result of the integer is 0 divided and calculated.

- INT I = 12/0;

- NullPointersException - Attempts to access objects when the object is not instantiated:

- DATE D = NULL;

- System.out.println (D. Tnowtring ());

- NegativeArraysizeException - An attempt to create an array of negative dimensions.

- ArrayIndexOfboundsexception - Try to access an element exceeding the array size range.

- SecurityException- is typically thrown into the browser, the SecurityManager class will throw an exception in Applets, which is attempting to do the following (unless it is obviously allowed):

- Access a local file

- Open a Socket of the host, this host is not the same as the host of the applet.

- Do another program in the runtime environment

Section 7 Processing or Statement Rules

Processing or declaration rules

- Treatment of exceptions with try-catch-finally block

- Declaring code can cause an exception using the throws clause

In order to write a strong code, the Java programming language requires that when a method is in the stack (ie, it has been called), the method must decide what to take if there is a problem. Measures.

The programmer can do two things to meet the requirements:

First, by incorporating the try {} catch () {} block into its code, the capture here is named as an exception that belongs to a superclass, and the method is called. This is also a handling even if the catch block is empty. Second, let the method being called indicate that it will not process an exception, and the exception will be thrown back into the calling method it encountered. It is implemented by declaration of this calling method tagged by the Throws clause as follows:

Public void Troublesome () THROWS IOException

Keyword throws is followed by all an exception list, and the method can be thrown back into its calling program. Although only one exception is only shown here, if there is a possible exception, it can be thrown through this method, then a comma-separated list can be used.

Is the selection processing or a declaration that an exception depends on whether a more suitable candidate for yourself or your calling program is given an exception.

Note - Since the abnormal class is like other classes, it is necessary to use a subclass because of when you want to use a superclass, it can capture the exception "group" and process them in the same capture code. For example, although IOExceptions (EOFEXCEPTION, FILENOTFoundException, etc., there are several different types, and instances of IOEXCEPTION can be captured by capturing IOException.

Section 8 Creates your own exception

7.8.1 Introduction

User-defined exception is created by extending the Exception class. This anomaly class can contain anything contained in the "Ordinary" class. Below is a user-defined anomaly class, which contains a constructor, several variables, and methods:

PUBLIC CLASS ServerTimedoutexception Extends Exception {

2. PRIVATE STRING

3. Private int port;

4. Public ServerTimedoutexception (String Reason, INT port) {

5. this.reason = Reason;

6. this.port = port;

7.}

8. Public string getreason () {

9. Return REASON

10.}

11. Public int getport () {

12. Return Port;

13.}

14.}

Use the statement to throw an exception that has been created:

Throw New ServerTimedoutexception

("Could Not Connect", 80);

7.8.2 instance

Consider a client server program. In the customer code, you should connect with the server and hope that the server responds within 5 seconds. If the server does not respond, then the code throws an exception (such as a user-defined serverTimedOutException) as described below.

Public Void ConnectMe (String ServerName) throws

ServerTimedoutexception {

2. INT Success;

3. INT portToconnect = 80;

4. Success = Open (ServerName, PortToconnect); 5. IF (Success == -1) {

6. Throw new servertimedoutexception

7. "Could Not Connect", 80);

8. }

9. }

To capture exceptions, use the try statement:

Public void findserver () {

2. . . .

3. TRY {

4. ConnectMe (DefaultServer);

5.} catch (servertimedoutexception e) {

6. System.out.Println ("Server Timed Out, Trying Alternate);

7. TRY {

8. ConnectMe (AlternateServer);

9.} catch (servertimedoutexception e1) {

10. System.out.Println ("No Server Currently Available);

11.}

12.}

13. ...

Note -Try and Catch blocks can be nested as described in the foreiot.

It is also possible to partially handle an exception and then throw it. Such as:

Try {

.....

.....

} catch (servertimedoutexception e) {

System.out.println ("Error Caught");

Throw e;

}

Exercise: Processing and creation exception

Exercise Purpose - Experience in an exception mechanism can be obtained by writing a Java software program that can create and process exceptions.

First, ready

In order to successfully complete the experiment, it is necessary to understand the concept of abnormalities in handling the runtime.

Second, the task

First class experiment: Treat an exception

1. Create an exception in the array index exceeding the array of array indexes on page 169. (Or modify your own procedure to create an exception.)

2. Use the TRY and CATCH statements to recover from exceptions.

Secondary experiment: Create your own exception

Use the BANK package created in module 5 and attach the following exception:

AccountoverDrawnexception - When this is to take out more money than the account.

INVALIDDEPOSISITEXCEPTION - When the number of invalid money (less than 0) is deposited.

Third, practice summary

Discuss - spend a few minutes to discuss the experience, problems or discovery of experimental exercises.

l Experience interpretation summary application

Fourth, check the progress

Check it before proceeding to the next module, confident that you can:

- definition exception

- Use TRY, CATCH and FINALLY statements

- Describe an exception classification

- Confirm common unusual

- Development procedure to deal with yourself

V. Thinking

What is the characteristics of the Java application environment that supports the development of the user interface?

转载请注明原文地址:https://www.9cbs.com/read-8103.html

New Post(0)