Thinking logic of computer programs (24) and thinking Logic

Source: Internet
Author: User

Thinking logic of computer programs (24) and thinking Logic

The basic types, classes, interfaces, and enumerations we introduced previously are all used to represent and operate data. There may be many errors during the operation process, and there may be many causes of errors, some are uncontrollable internal reasons, such as insufficient memory, full disk, and some are uncontrollable external reasons, such as network connection problems, and more may be program errors, for example, if the referenced variable is not initialized, the instance method is called directly.

These exceptions are regarded as exceptions in Java. Java uses the exception mechanism for unified processing. Due to the large amount of content, we will introduce them in two sections. This section introduces the preliminary concepts of exceptions, and exception classes. Next section describes how to handle exceptions.

Let's first look at the exceptions through some examples.

Initial exception

NullPointerException (NULL pointer exception)

Let's look at the code section:

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

If the variable s is not initialized, its instance method indexOf is called to run. The screen output is:

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

The output tells us that, in the main function of the ExceptionTest class, there is a null pointer exception (java. lang. NullPointerException) In line 5th of the Code ).

But what happened? When s. when indexOf ("a"), the Java System finds that the value of s is null and there is no way to continue the execution. In this case, the exception handling mechanism is enabled. First, an exception object is created, here is the NullPointerException-like object, and then find out who can handle this exception. In the sample code, if no code can handle this exception, Java will enable the default processing mechanism, that is, print the abnormal stack information to the screen and exit the program.

When introducing the function call principle, we introduced the stack. The exception stack information includes the trace from the abnormal occurrence point to the top caller, and also contains the row number. It can be said that, this stack information is the most important information for analyzing exceptions.

Java's default Exception Handling Mechanism is to exit the program, and the code after the exception occurrence is not executed, so the last line of System. out. println ("end") in the sample code is not executed.

NumberFormatException (numeric format exception)

Let's take an example. The Code is as follows:

Public class ExceptionTest {public static void main (String [] args) {if (args. length <1) {System. out. println ("enter a number"); return;} int num = Integer. parseInt (args [0]); System. out. println (num );}}

Args indicates a command line parameter. This Code requires that the parameter be a number. It converts the parameter to an Integer through Integer. parseInt and outputs this Integer. The parameter is input by the user. We cannot force the user to enter anything. If the user inputs a number, such as 123, the screen outputs 123. However, if the user inputs a number, such as abc, the screen will 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)

NumberFormatException occurs. How did this exception occur? Based on the exception stack information, let's look at the relevant code:

This is the code near the 65 lines of the NumberFormatException class:

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

This is the code near the Integer class line 492:

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 }

Merge the two parts into one line. The main code is:

throw new NumberFormatException(...)

New NumberFormatException (...) is easy to understand. It creates a class object, but this class is an exception class. What does throw mean? An exception is thrown, which triggers the Exception Handling Mechanism in Java. In the previous NULL pointer exception, we did not see the throw code. We can think that throw is implemented by the Java Virtual Machine itself.

The throw keyword can be compared with the return keyword. return indicates normal exit, throw indicates abnormal exit, and the return position of return indicates the upper-level caller, which line of code is executed after throw is often uncertain and dynamically determined by the exception handling mechanism.

The exception handling mechanism starts from the current function to check who "caught" the exception. If the current function does not exist, check the previous layer until the main function does not exist, the default mechanism is used to output abnormal stack information and exit. This is exactly what we see in the screen output.

Programmers can understand the exception stack information in the screen output, but ordinary users cannot understand and do not know what to do. We need to give users a more friendly information and tell them, he should enter a number. To do this, we need to "catch" the exception.

"Capture" refers to the use of the try/catch keyword. Let's look at the sample code after an exception is caught:

Public class ExceptionTest {public static void main (String [] args) {if (args. length <1) {System. out. println ("enter a number"); return;} try {int num = Integer. parseInt (args [0]); System. out. println (num);} catch (NumberFormatException e) {System. err. println ("parameter" + args [0] + "is not a valid number. Please enter a number ");}}}

We caught and handled exceptions using try/catch. The braces {} After try contain the code that may throw an exception. The catch statement after the parentheses contains the caught exception and processing code, catch contains the exception information in brackets, including the exception type and variable name. Here is NumberFormatException e, which can be used to obtain more exception information. The code is processed in braces, A more friendly prompt is provided here.

After an exception is caught, the program will not exit unexpectedly, but other code after the exception point in the try statement will not be executed. After the catch statement is executed, the program will continue to execute the catch code out of braces.

In this way, we have a preliminary understanding of exceptions. Exceptions are an exit mechanism relative to return, which can be triggered by the system or by the program through throw statements, exceptions can be captured and processed using try/catch statements. If exceptions are not captured, the program exits and the exception stack information is output. Exceptions have different types. Next, let's take a look.

Exception

Throwable

Both NullPointerException and NumberFormatException are exception classes. All exception classes share a common parent class Throwable, which has four public constructor methods:

  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: message, indicating the exception message, and cause, indicating other exceptions that trigger the exception. Exceptions can form an exception chain. The upper-layer exceptions are triggered by the underlying exceptions. cause indicates the underlying exceptions.

Throwable also has a public method for setting cause:

Throwable initCause(Throwable cause)

Some subclasses of Throwable can be set using this method without the constructor with the cause parameter. This method can be called at most once.

There is an important function call in all constructor methods:

fillInStackTrace();

It saves the exception stack information, which is the key to seeing the exception stack.

Throwable has some common methods for obtaining exception information:

void printStackTrace()

Print the exception stack information to the standard error output stream. There are two methods to reload the stack:

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

Prints stack information to the specified stream. We will introduce PrintStream and PrintWriter in subsequent articles.

String getMessage()Throwable getCause()

Obtain the set exception message and cause

StackTraceElement[] getStackTrace()

Obtains information of each layer of the exception stack. Each StackTraceElement includes information such as the file name, class name, function name, and row number.

Exception System

Taking Throwable as the root, many exception classes are defined in Java APIs, indicating various types of exceptions. The following table lists some types of exceptions:

Throwable is the base class of all exceptions. It has two subclasses: Error and Exception.

Error indicates a system Error or resource depletion, which is used by the Java system itself. The application should not throw and handle it, such as the virtual machine Error (VirtualMacheError) listed in and its sub-class memory overflow Error (OutOfMemoryError) and stack overflow error (StackOverflowError ).

Exception indicates an application error. It has many sub-classes. The application can also create custom exceptions by inheriting Exception or its sub-classes. The following figure lists three direct sub-classes: IOException (input/output I/O exceptions), SQLException (Database SQL exceptions), and RuntimeException (runtime exceptions ).

RuntimeException (runtime exception) is special, and its name is a bit misleading, because other exceptions are also generated during runtime. It indicates the actual meaning is unchecked exception (uncheckexception ), in contrast, the other subclass of Exception and Exception itself are checked exception (checked exception), and the Error and its subclass are also unchecked Exception.

The difference between checked and unchecked lies in how Java handles these two types of exceptions. For checked exceptions, Java will force programmers to handle them; otherwise, compilation errors may occur, but unchecked exceptions do not. Next we will explain it further.

RuntimeException also has many subclasses. The following table lists some of them:

Exception Description
NullPointerException Null Pointer exception
IllegalStateException Invalid status
ClassCastException Illegal forced type conversion
IllegalArgumentException Parameter Error
NumberFormatException Incorrect Number Format
IndexOutOfBoundsException Index out of bounds
ArrayIndexOutOfBoundsException Array Index out of bounds
StringIndexOutOfBoundsException String Index out of bounds

So many different exception classes do not actually have much more attributes and methods than the Throwable base class. Most classes only define several constructor Methods After inheriting the parent class, these constructor only calls the constructor of the parent class and does not perform any additional operations.

So why do we define so many different classes? The main reason is that the name of the exception class is different. The name of the exception class itself represents the key information of the exception. When an exception is thrown or caught, using a proper name will help the code to be readable and maintainability.

Custom exception

Apart from the Exception classes defined in Java APIs, we can also define the Exception classes by ourselves. Generally, by inheriting Exception or a subclass of it, if the parent class is RuntimeException or a subclass of it, the custom exception is also an unchecked Exception. If it is an Exception or another subclass of exception, the custom exception is a checked Exception.

We define an Exception by inheriting the Exception. The Code is as follows:

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);    }}

Like many other Exception classes, we do not define additional attributes and code, but inherit the Exception, define the constructor and call the constructor of the parent class.

Summary

In this section, we will give a basic introduction to exceptions through two examples, introduce the try/catch and throw keywords and their meanings, and introduce the Throwable and the exception class system rooted in it.

Next section, let's further explore exceptions.

----------------

For more information, see the latest article. Please pay attention to the Public Account "lauma says programming" (scan the QR code below), from entry to advanced, ma and you explore the essence of Java programming and computer technology. Write with your heart, original articles, and retain all copyrights.

-----------

More original articles

Thinking logic of computer programs (1)-data and variables

Thinking logic of computer programs (5)-Why is an error in decimal calculation?

Thinking logic of computer programs (6)-How to recover from garbled code (I )?

Thinking logic of computer programs (8)-true meaning of char

Thinking logic of computer programs (12)-Basic Principles of function calls

Thinking logic of computer programs (17)-Basic Principle of inheritance implementation

Thinking logic of computer programs (18)-Why inheritance is a double-edged sword

Thinking logic of computer programs (19)-essence of interfaces

Thinking logic of computer programs (20)-Why abstract classes?

Thinking logic of computer programs (21)-nature of internal classes

Thinking logic of computer programs (23)-nature of enumeration

 

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.