Abnormal handling in Java

xiaoxiao2021-03-05  21

Distant

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 exceeds a predetermined range

Very interested in being loaded

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.

First, abnormal processing

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

1 TRY and CATCH statement

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 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.}

If a statement in the fruit method throws an exception that is not processed in the corresponding TRY / CATCH block, then this exception is thrown into the modified 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.

In this case, 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.

2 Finally statement

The Finally statement defines a single code block that is always executed without considering whether the abnormality is captured.

TRY {

2. Startfaucet ();

3. Waterlawn ();

4.}

5. finally {

6. stopfaucet ();

7.}

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. Second, abnormal 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 indicates a serious problem that recovery is not impossible 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 will never do this, 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 runtime, 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.

Third, common unusual

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

The arithmeticException-integer is divided by 0, and the result is obtained. INT i = 12/0;

NullPointersException - Attempts to access objects when the object is not instantiated, attempts to access objects: date d = null; system.out.println (d.toString ());

NegativeArraysizeException - Create an attempt to create an array of negative dimension.

ArrayIndexOfboundSexception - Try to access an element that exceeds the array size range.

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

l Access a local file

l Open a socket of the host, this host is not the same as the host of the applet.

l Execute another program in the runtime environment

Fourth, handling or declaration rules

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 called in the hierarchy, it must be used to use a subclass because of when you want to use a superclass, it can capture the exception "group" and processes them with 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.

V. Create your own exception

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 one {

Public static void main (string str []) throws servertimedoutexception {

Throw New ServerTimedoutexception ("Could Not Connect", 80); // Use the statement to throw an exception that has been created

}

}

Class ServerTimedoutexception Extends Exception {

PRIVATE STRING

PRIVATE INT Port;

Public ServerTimedoutexception (String REason, INT port) {

this.reason =.

THIS.PORT = Port;

}

Public String getreason () {

Return REASON

}

Public int getport () {

Return port;

}

}

Example: 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. ...

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;

}

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

New Post(0)