Java programming logic (24) - abnormal (on)

Before we introduce the basic types, classes, interfaces, enumerations are representing and manipulating data, process operations may have a lot of things go wrong, the wrong reasons may be many, some internal causes uncontrollable, such as memory not enough, the disk is full, some uncontrollable external factors, such as network connection problems, may be more procedural programming errors, such as uninitialized variables referenced directly invoke instance methods.

These non-normal conditions are considered abnormal, use the Java exception mechanism in Java to unify treatment unified, as more content, we divided into two to reports, this section describes the initial concept abnormal, and abnormal class itself, under the main section introduction handle exceptions.

Let's come through some examples to learn what anomalies.

The initial abnormal

A NullPointerException (null pointer exception)

Let's look at the code section:

Copy the code
public class ExceptionTest {
    public static void main(String[] args) {
        String s = null;
        s.indexOf("a");
        System.out.println("end");
    }
}
Copy the code

The variable s is not initialized method is called the indexOf examples, operation of the screen output:

Exception in thread "main" java.lang.NullPointerException
    at ExceptionTest.main(ExceptionTest.java:5)

The output is telling us: the main function ExceptionTest class, the code line 5, there was a null pointer exception (java.lang.NullPointerException).

But, what specifically happened then? When the execution s.indexOf ( "a") is, Java system finds the s value is null, there is no way to proceed, and then you enable exception handling mechanism, first create an exception object, here is the class NullPointerException object, and then look to see who can handle the exception, in the sample code, the code can not handle the exception, Java is enabled by default handling mechanism, that is, print exception stack information to the screen, and exit the program.

When introduced function calls principles, we introduced the stack, the exception stack information including from abnormal point to track the uppermost layer of the caller, also includes line numbers, we can say that the stack information is to analyze the anomaly of the most important information.

Java's default exception handling mechanism is to exit the program, code point exception occurs is not enforced, so the sample code in the last line System.out.println ( "end") will not be executed.

A NumberFormatException (abnormal digital format)

Let us look at an example, the following code:

Copy the code
public class ExceptionTest {
    public static void main(String[] args) {
        if(args.length<1){
            System.out.println("请输入数字");
            return;
        }
        int num = Integer.parseInt(args[0]);
        System.out.println(num);
    }
}
Copy the code

args parameter indicates that the command line, the code requires a number of parameters, the conversion parameters that Integer.parseInt by an integer, and outputs the integer. Parameters are entered by the user, we have no way to force users to enter what, if you lose a number, such as 123, 123 screen output, but if the user input is not a number, such as abc, screen output:

Exception in thread "main" java.lang.NumberFormatException: For input string: "abc"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:492)
    at java.lang.Integer.parseInt(Integer.java:527)
    at ExceptionTest.main(ExceptionTest.java:7)

Appeared abnormal NumberFormatException. This anomaly is how to generate it? According exception stack information, we look at the relevant code:

This is close to 65 NumberFormatException class lines of code:

64 static NumberFormatException forInputString(String s) {
65     return new NumberFormatException("For input string: \"" + s + "\"");
66 }

This is close to 492 lines of code Integer class:

Copy the code
490 digit = Character.digit(s.charAt(i++),radix);
491 if (digit < 0) {
492     throw NumberFormatException.forInputString(s);
493 }
494 if (result < multmin) {
495     throw NumberFormatException.forInputString(s);
496 }
Copy the code

These two combined into one line, the main code is:

throw new NumberFormatException(...)

new NumberFormatException (...) we are easy to understand, it is to create an object of a class, but this class is an exception class. throw What does it mean? That is, an exception is thrown, it will trigger the Java exception handling mechanism. Before the null pointer exceptions, we do not see throw the code may be considered by the Java Virtual Machine throw their own implementation.

throw keyword with the return keyword contrast, represents the return to normal exit, throw representatives abnormal exit, return return position is determined, that is, on the one caller, and which line of code is executed after throw it often is uncertain, dynamically determined by the exception handling mechanism.

Exception handling mechanism will start looking to see who from the current function "capture" the exception, not the current function to view a layer, until the main function, if there is no main function, the default mechanism, the exception stack output information and exit, this is what we see in the screen output.

For the exception stack information screen output, the programmer is understandable, but ordinary users can not understand, do not know how to do, we need to give users a more friendly message telling the user that he should enter a number, to do this, we need our own "capture" exception.

"Capture" refers to the use try / catch keyword, we look at the sample code after the capture of an exception:

Copy the code
{class ExceptionTest public 
    public static void main (String [] args) { 
        IF (args.length <. 1) { 
            System.out.println ( "Enter a number"); 
            return; 
        } 
        the try { 
            int NUM = the Integer.parseInt (args [0]); 
            System.out.println (NUM);     
        } the catch (a NumberFormatException E) { 
            System.err.println ( "parameter" + args [0] 
                    + "is not a valid number, enter a number"); 
        } 
    } 
}
Copy the code

We use the try / catch exception captured and processed, the try back braces {} may comprise the code throws an exception, the bracket comprising a catch statement and exception handling code can be captured, the rear catch brackets abnormality information, comprising variable name and type of exception, this is NumberFormatException e, abnormality can get more information which is handling code within the braces {}, there is outputted a more friendly message.

After the catch the exception, the program will not quit unexpectedly, but other code after the outliers in the try statement will not be executed, and after completion of the implementation of the statements within the catch, the program will continue to execute code outside the braces catch.

In this way, we are on the anomaly have a preliminary understanding, the anomaly is relative to the type of exit mechanism to return, and can be triggered by the system can also be triggered by the program by the throw statement, an exception can be captured by a try / catch statement and processing, If not caught, it will cause the program to exit and output exception stack information. There are different types of abnormal, then, we come to know about.

Exception class

Throwable

NullPointerException and are NumberFormatException exception class, exception classes all have a common parent class Throwable, which has four public constructor:

  1. public Throwable()
  2. public Throwable(String message)
  3. public Throwable(String message, Throwable cause)
  4. public Throwable(Throwable cause) 

There are two main parameters, a message, a message indicating an abnormality, the other is the cause, indicate triggering the exception of other abnormalities. And form a chain of abnormal abnormality, abnormality abnormality triggered by the upper bottom, the bottom represents the cause is abnormal.

Throwable there is provided a method for a public cause:

Throwable initCause(Throwable cause)

Some Throwable subclass constructor cause with no parameters, it can be set by this method, this method can only be called at most once.

All constructor has an important function call:

fillInStackTrace();

It will be an exception stack saved information, which we can see the key exception stack.

Throwable There are some common methods used to obtain exception information:

void printStackTrace()

Print exception stack error information to the standard output stream, there are two overloaded methods:

void printStackTrace(PrintStream s)
void printStackTrace(PrintWriter s)

Print stack information to the specified stream, PrintStream and PrintWriter on our follow-up article describes.

String getMessage()
Throwable getCause()

Get Set and cause abnormal message

StackTraceElement[] getStackTrace()

Acquiring information of each layer exception stack, each including StackTraceElement information file name, class name, function name, line number, and the like.

Exception class system

Throwable to the root, Java API defined in a lot of exception classes representing various types of abnormal portions indicate the following categories:

Throwable is a base class for all exceptions, it has two subclasses and Error Exception.

Error a system error or resource exhaustion, used by the Java system itself, the application should be thrown and processing, virtual machine error (VirtualMacheError) such as the figure listed in its subclasses memory overflow errors (OutOfMemoryError) and a stack overflow error (StackOverflowError).

Exception application error indicates that there are many subclasses, applications can create custom exception Exception by inheritance or subclass, direct drawing lists three subclasses: IOException (input-output I / O exception), SQLException (SQL database anomalies), RuntimeException (a runtime exception).

RuntimeException (a runtime exception) is rather special, its name is a bit misleading, because other exception is generated run-time, the actual meaning it represents is unchecked exception (not Unchecked exceptions), relatively speaking, the other subclasses of Exception and Exception itself is checked exception (abnormal subjects), Error and its subclasses are unchecked exception.

checked or unchecked, the difference lies in how to handle both Java exception for checked exceptions, Java programmers will be mandatory, otherwise there will be a compilation error, and for unchecked exceptions do not have this requirement. The next section will explain further.

RuntimeException there are many sub-categories, the following table lists some of the common ones:

abnormal Explanation
NullPointerException Null pointer exception
IllegalStateException Illegal status
ClassCastException Illegal cast
IllegalArgumentException Parameter error
NumberFormatException Digital format error
IndexOutOfBoundsException Index out of bounds
ArrayIndexOutOfBoundsException Array index out of bounds
StringIndexOutOfBoundsException String index out of bounds

So many different exception classes and in fact the number of properties and methods Throwable no more than the base class, most of the class inherits the parent class after only defines several construction methods, these constructor just calls the parent class constructor, and no additional operations.

So why are so many different definitions of classes it? Mainly for different names, the exception class name itself represents an exception key information, whether it is thrown or catch the exception, use the appropriate name will help the readability and maintainability of the code.

Custom exception

In addition to abnormal Java-defined API, we can also define your own exception classes, usually through inheritance Exception or one of its sub-categories, if the parent class is RuntimeException or one of its sub-categories, then the custom exception is unchecked exception, if it is exception exception or other subclass, the custom exception is checked exception.

We define an exception by extending Exception, the following code:

Copy the code
public class AppException extends Exception {
    public AppException() {
        super();
    }

    public AppException(String message,
            Throwable cause) {
        super(message, cause);
    }

    public AppException(String message) {
        super(message);
    }

    public AppException(Throwable cause) {
        super(cause);
    }
}
Copy the code

And many other exception classes, we do not define additional properties and code, just inherited the Exception, the definition of a constructor and call the constructor of the parent class.

summary

In this section, we have two examples of anomalies do basic introduction, describes the try / catch and throw keywords and their meanings, and also introduced Throwable exception to it as the root class system.

The next section, let us further explore anomalies.

      

Guess you like

Origin www.cnblogs.com/ivy-xu/p/12387614.html