Getting Started in Java - Chapter 8 Java's "Abnormal"

zhaozj2021-02-17  60

Chapter 8 Java's "Abnormal"

"Isometric" refers to the current non-normal situation in the program operation. When programming with a traditional language, the programmer can only send an error message with the return value of the function. This is easy to lead to many wrong mistakes, because it is necessary to know the internal detail of the wrong childhood. Typically, the type of "different" is stored with the full-local variable errno. This is easier to cause misuse, because the value of an errno can be processed? REG; before being overwhered by another error. That is to make the best C language program, it is a "different" situation, and it is often necessary to help the goto statement. Java's treatment of "common" is facing the object. A Java's Exception is an object that describes the "different" situation. When the "other" situation is now, an Exception object is born and put it into a "other" members of the "different".

8.1 foundation

Java 's "different" processing is to achieve 5 keywords: try, catch, throw, throws and finaLY. Use TRY to execute a program, if "exception", system throws (throws? Copy; a "exception", you can capture (Catch? Copy; it, or final (FINALL? Copy; The provincial processor is handled. The following is the basic form of the "exception" handler:

Try {// program block} catch (ExceptionType1 E) {// Processing THROW (E) for ExceptionType2 {// {// {} {} {} {}}}; //

8.2 Types of "different"

There is a single-unique class called THROWABLE. This class is used to indicate the "different" situation. Each "different" type is the Subclass of Throwable. Throwable has two direct subclasses. One class is Exception, which is the "different" situation that can capture enough to capture. We will create its own "different" through the child of generating it. The other is Error, which is defined? Copy; unmanageless "different". Be cautiously use Error subclasses, because they will often lead to disaster relief. There is a subclass RuntimeException in Exception, which is automatically somewhat in the program run. Copy; misfinally misunderstandings.

8.3 Do not catch "different"

"Isometric" pair is a matter of Java to be in a time when it is running. For example, the lower program contains an integer to be "different".

Class Exc0 {public static void main (string args []) {INT D = 0; int A = 42 / d;}}

When Java performs this division, since the denominator is 0, it will construct a "exception" object to stop the program to stop and handle this error, "throw" when running (throw? Copy; this "exception". Say " Throw "is because it is like a hot potato, you must seize it and immediately. The program flow will be interrupted at the division operator, then check the current call stack to find" exception ". One" The exception "processor is used to process" exception "situation immediately. In this example, we did not have a" exception "processor, so the default processor played. Default processor prints the character of Exception REG; value and "exception" location. Below is the output of our small example .c: /> java eXC0 java.lang.arithmeticException: / by zero at eXc0.main (exc0.java: 4)

8.4 Try and Catch

Tongmong us hope that he has to handle "other" and continue to run. You can use TRY to specify a piece of pre-prevention of all "distant". Tightly follow the Try program, it should be included in a Catch clause to specify the type of "different" you want to catch. For example, the following example is configured on the basis of the previous example, but it contains a TRY program block and a Catch clause.

Class Exc1 {public static void main (string args []) {Try {INT D = 0; INT A = 42 / d;} catch (arithmeticexception e) {system.out.println ("Division By Zero");}} }

The goal of the Catch clause is to solve the "different" situation, put one? copy; variable to the reasonable state, and continue to run like there is no error. If a subscriber is not processed, it is returned to the previous level, until the outermost level.

8.5 multiple catch clauses

In a case? Copy; if the situation, the same period may produce more than one "abnormal" situation. You can put multiple Catch clauses, each "other" type type will be checked, the first and? REG; match will be executed. If there is a class and its subclasses, the subcaters should be placed in front, and they will never reach the subclasses. The lower surface is an example of the program of two CATCH clauses.

Class multicatch {public static void main (string args []) {Try {Int a = args.length; system.out.println ("a =" a); int b = 42 / a; int C [] = { 1}; CATCH (ARTHMEXOFBOUNDLN ("ArrayIndexoutofboundSException E)} catch (arrayindexoutofboundsexception e) {system.out.println (" Array Index OOB) : " E);}}} If the program is not with parameters when the program is running, it will cause" exception "to be divided by 0, because the value of A is 0. If we mentioned? Copy; a command line parameter will not produce this "different", because the value of A is greater than 0. However, it will lead to "distant" of arrayindexoutofboundexception, since the length of the integer group C is 1, but is assigned to C [42]. The lower surface is the result of the above two cases.

C: /> java multicatch a = 0 Div By 0: java.lang.arithmeticexception: / by zero c: /> java muticatch 1 a = 1 Array Index Oob: java.lang.ArayindexOutofboundsexception: 42

8.6 Nested of TRY sentence

You can write a TRY statement in the outside of a member function call, in this membership function, write another TRY sentence to protect his code. Whenever a try statement is encountered, the "other" frame is placed on the stack until all TRY sentences are completed. If the next level of the TRY sentence does not have a "other" to proceed, the stack will be open until it encounters the Try statement of "different". The lower surface is an example of a TRY statement.

Class multinest {static void procedure () {Try {int C [] = {1}: C [42] = 99; arrayindexoutofboundsexception e) {system.out.println ("Array Index OOB: E); }}} public static void main (string args []) {Try {Int a = args.length; system.out.println ("a =" a); int b = 42 / a; procedure ();} catch ArithmeticException E) {system.out.println ("DIV BY 0:" E);}}}

There is a self-controlled TRY / CATCH control in the member function Procedure.

8.7 THROW statement

The throw statement is used to throw a "different". First, you must get a control handle of a Throwable instance, pass the parameters to the Catch clause, or create one with the new operation. The lower surface is the normal form of the throw statement. Throw throwableinstance;

The program will be finally terminated after the throw statement, and the lack of statement is not performed, and then looks out to the TRY block containing the CatCH clause that matches it in all the TRY blocks containing it. The lower surface is an example containing the throw statement.

class ThrowDemo {static void demoproc () {try {throw new NullPointerException ( "de3mo");} catch (NullPointerException e) {System.out.println ( "caught inside demoproc"); throw e;}} public static void main ( String args []) {Try {Demoproc ();} catch (nullpointers) {system.out.println ("RECAUGHT: E);}}}

8.8 THROWS statement

THROWS is used to mark a variety of "different" that can be thrown out. For large number of Exception subclasses, the Java compiler will force you to speak the type of "different" that throws out in a member function. If the type of "different" is ERROR or RUNTIMEEXCEPTION, or its subclasses, this rule does not work, because this is this? Copy; in the regular sequence of the program, it is not expired. If you want to make a runtimeException, you must use the THROWS statement to clear its type. This will redefine the definition of the functionality of the member function:

TYPE METHOD-NAME (arg-list) throws exception-list {}

The lower surface is a piece of step, which throws a "different", but neither can't capture it, and it is not possible to speak with throws. This will not pass during complication.

class ThrowsDemo1 {static void procedure () [System.out.println ( "inside procedure"); throw new IllegalAccessException ( "demo");} public static void main (String args []) {procedure ();}}

For this example, we need to be able to invoice the membership function Procedure throws IllegalaccessException and captures it in the member of the members. The lower surface is the correct example:

class ThrowsDemo {static void procedure () throws IllegalAccessException {System.out.println ( "inside procedure"); throw new IllegalAccessException ( "demo");} public static void main (String args []) {try {procedure (); } catch (illegalaccessException e) {system.out.println ("Caught" E);}}} The following is the output result:

C: /> java throwsdemo inside procedure caught java.lang.illegalaccessException: Demo

8.9 Finally

When a "different" is thrown out, the execution of the program is no longer linear, skips it? Copy; line, even if there is no? REG; match Catch clause, it will return early. If you have any code, you don't have a code. If you are, "other" is executed, it is necessary, the keyword Finally is used to identify this code. That is, you don't have a Catch clause, and the Finally program block will also perform the procedure after the trory sequence block. REG; Each TRY statement needs to be at least one of the Catch clause or the FinalLy clause of the match. A member function returns to the member function of calling it, or passes a unfaised "different", or a clear Return statement, the Finally clause is always right in front of the membership function. The next is an example, which has several members of the function, and each member function is retired by the different route, but the finally clause is performed.

class FinallyDemo {static void procA () {try {System.out.println ( "inside procA"); throw new RuntimeException ( "demo");} finally {System.out.println ( "procA's finally");}} static Void procb () {type {system.out.println ("inside procb"); return;} finally {system.out.println ("procb's finally");}} public static void main (string args []) {TRY {proca ();} catch (exception e); procb ();}}

The lower surface is the results of this example:

C: /> Java FinallyDemo Inside Proca Proca's Finally Inside Procb Procb's Finally

chapter summary

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

New Post(0)