201621123034 Java programming 10th Week of study summary

Source: Internet
Author: User
Tags finally block set time

Job 10-Exception 1. This week's study summary 1.1 summarizes anomalies related content in the way you like (mind map or other).

2. Written work

This PTA work problem set异常

1. Common exceptions

7-1 answer with topic set

1.1 What exceptions do you often have in code that you have written before, and what do you need to capture (why)? What should be avoided?

For:

Exceptions and exceptions are frequently seen in code that you have previously written, and ArrayIndexOutOfBoundsException RuntimeExecption do not need to be captured because only exceptions that are directly inherited are Exception required to be captured.

1.2 What kind of exception requires the user to be sure to use capture processing?

Answer: Exception the exception that inherits directly from

2. Handle exceptions to make your program more robust

Topic 7-2

2.1 Experimental summary. And answer: How can you make your program more robust?

A: After the array is created, the input characters are stored in an array, the contents of the array are read, and the exception information is output using the Try-catch captured array in the non-shaped string.

The trouble is that if the array is read with only the i++ in the For loop, then when the non-shaping string is encountered, not only the exception is caught, but also the error is i++, and the processing method is as follows:

Use Try-catch to catch exceptions and return exception information.

3. Throw and throws

Topic 7-3
Read the Integer.parsetInt source code

3.1 Integer.parsetIntWhat is the benefit of having a large number of code throwing exceptions at the outset?

For:
Source:

    public static int parseint (String s, int radix) throws NumberFormatException {/* * W Arning:this method may be invoked early during VMS initialization * before Integercache is initialized.         Care must is taken to does use * the ValueOf method.        */if (s = = null) {throw new NumberFormatException ("null");                                            } if (Radix < Character.min_radix) {throw new NumberFormatException ("radix" + Radix +        "Less than Character.min_radix");                                            } if (Radix > Character.max_radix) {throw new NumberFormatException ("radix" + Radix +        "Greater than Character.max_radix");        } int result = 0;        Boolean negative = false;        int i = 0, Len = s.length ();        int limit =-integer.max_value;        int multmin;        int digit; if (Len > 0) {char Firstchar = S.charat (0); if (Firstchar < ' 0 ') {//Possible leading "+" or "-" if (Firstchar = = '-') {Negativ                    E = true;                Limit = Integer.min_value;                } else if (firstchar! = ' + ') throw numberformatexception.forinputstring (s);                if (len = = 1)//cannot has lone "+" or "-" throw numberformatexception.forinputstring (s);            i++;            } multmin = Limit/radix; while (I < len) {//accumulating negatively avoids surprises near max_value digit = Char                Acter.digit (S.charat (i++), radix);                if (Digit < 0) {throw numberformatexception.forinputstring (s);                } if (Result < Multmin) {throw numberformatexception.forinputstring (s);                } result *= radix; if (Result < limit + digit) {                   Throw numberformatexception.forinputstring (s);            } result-= digit;        }} else {throw numberformatexception.forinputstring (s); } return negative?    Result:-result; }

Benefits: Unify the various anomalies in the place, no need to write a variety of error-making methods to interfere with the code logic, and then all the problems in the back of the unified processing, the code logic and error handling separate to facilitate the subsequent writing and maintenance.

3.2 What information do you usually need to pass to the caller when you write your own program with 3.1 and analyze your own method of throwing an exception?

For:

Information to be passed to the caller: the cause of the exception and the number of rows of the exception

4. Improve Arrayintegerstack with exception

Topic 6-3

4.1 In combination with 6-3 code, how does it benefit to use an exception-throwing method to represent a program run-time error? What is the advantage of returning an error value more than a simple one?

For:

Benefit: When a code run encounters an error, the method ends immediately, does not return a value, and throws an exception object to be able to clearly know what the exception occurred.

Pros: A simple return error value is when an exception occurs, the function returns a special result, and we need to call the function of the program is responsible for checking and analyzing the function returned to know what the exception, and the way to throw an exception on behalf of the program runtime error will be able to clearly know what happened to the exception, for processing.

4.2 If an inner code inside a method throws an exception of type RuntimeException, then the method declaration should use the throwskeyword, if you use the throwsKeyword declares the exception thrown by this method, what benefits can it bring to us?

For:
RuntimeExceptionCan be generated in any code, do not need to use the throws keyword thrown, once the error occurs, then the corresponding exception will be automatically thrown. If you use it again throw to throw an RuntimeException exception, the compilation works, but it seems to be superfluous.

5. Function questions-capture of multiple exceptions

Topic 6-1

5.1 Combined with 6-1 code, answer: If you can throw multiple exceptions in a try block, and there may be an inheritance relationship between exceptions, what do you need to be aware of when capturing?

For:

Note: If you can throw multiple exceptions in a try block, and there may be an inheritance relationship between exceptions, you need to write multiple catch words to capture, and the child classes are captured in front of the parent class

5.2 If you can throw multiple exceptions in a try block, what do you need to be aware of when using Java8 's multiple exception capture syntax?

Answer: Exceptions in catch blocks must not have an inheritance relationship

6. Add exception handling to the following code
byte[] content = null;FileInputStream fis = new FileInputStream("testfis.txt");int bytesAvailabe = fis.available();//获得该文件可用的字节数if(bytesAvailabe>0){    content = new byte[bytesAvailabe];//创建可容纳文件大小的数组    fis.read(content);//将文件内容读入数组}System.out.println(Arrays.toString(content));//打印数组内容
6.1 Correct the code and add the following functions. When the file is not found, you need to prompt the user 找不到文件xxx,请重新输入文件名, and then try to turn it back on. Prompt if it is a different exception 打开或读取文件失败!

Note 1: There are several methods inside that can throw an exception.
feature 2: need to add finally close file. Always prompt, regardless of whether the above code produces an exception 关闭文件ing . If closing the file fails, prompt关闭文件失败!

For:

6.2 Combined Problem Sets 6-2Code, what do you want to put in the finally block? Why? What do I need to be aware of when closing resources using finally?

For:
Finally, the operation:

Because the file closes after the action is closed and prompts 关闭文件ing , the exception is caught and prompted if the file fails to close 关闭文件失败! .

Attention:
If fis = new FileInputStream("d:testfis.txt"); the code is wrong, FIS is not initialized, execution fis.close will report null pointer exception

The null pointer exception can be avoided by adding an empty

If an fis,close error occurs, the program jumps directly to it catch and cannot close the resource properly.

6.3 Using the Java7 in the try-with-resourcesTo rewrite the above code to automatically close the resource. What are the benefits of this approach?

For:

Benefit: The try-with-resources declaration ensures that the resources opened in the Declaration at the end of the declaration are closed, and that no manual write finally is required to close the resource.

7. Object-oriented design job-Library management system (group completion, no more than 3 students per group)

Log in to lib.jmu.edu.cnto search for books. Then log in to the library information system to view my library . If you want to implement a book borrowing system, try using object-oriented modeling.

7.1 Who is the user of this system?

Answer: Students, teachers, administrators

7.2 Main function modules (not too many) and the owner of each module. Next week everyone is going to submit their own module code and run the video.

For:
Students, teachers:

    • Registered
    • Login
    • Personal information
    • Search for book information
    • Borrowing books
    • Return
    • Exit

Administrator:

    • Login
    • Add a book
    • Delete a book
    • View book information
    • Change book information
    • Exit
7.3 Main class design and class diagram of the system (available)

For:

7.4 How you plan to store library information, address information, reader information, and more.

A: Use the ArrayList dynamic array to process the various information of the book and save the change information to the file when exiting the system.

8. Select: Use exceptions to improve your shopping cart system

Give 1 examples of how you can use the exception handling mechanism to make your program more robust.
The description consists of 2 parts: 1. The problem description (where the exception is encountered). 2. Solution (Key Code)

9. Select: Use the static Code scanning Tool to scan your shopping cart code 8.1 to analyze the specifications in your own code. 8.2 Think about how to solve these problems. 3. Code Cloud and PTA

Topic Set: Exceptions

3.1. Code Cloud codes Submission record

In the Code cloud Project, select statistics-commits history-set time period, and then search for and

3.2 PTA Problem set complete situation diagram

Two graphs are required (1. Ranking chart. 2.PTA Submission list diagram)

3.3 Count the amount of code completed this week

The weekly code statistics need to be fused into a single table.


Week Time Total code Amount New Code Volume total number of files number of new files
2 141 141 6 6
3 445 380 10 3
5 871 426 16 6
6 1496 623 26 10
7 2570 1076 40 14
8 2674 104 46 6
9 2997 323 53 7
10 3313 316 58 5
11 3724 411 68 10
Option: 4. Expand

Extracurricular exercises

Javatutorial in questions and exercises
Practice Summary

Extracurricular reading

Select one of the following articles to read and enumerate some of the best practices for exception handling that you can understand.
Best Practices for Exception handling
Exception-handling Antipatterns Blog
The Exceptions debate

Optional: 5. Use Java to solve practical problems (attendance Auto-statistics)

Association check-in, each time using a paper signature table to check in, go back and then manually statistics. If you have more than one signature table, manual statistics are required. Now keep the paper signature method unchanged, responsible for each time the paper signature table will be manually entered after the system, so that the data can be automatically counted. What functional modules are required to implement such a system? Try encoding implementation

201621123034 Java programming 10th Week of study summary

Related Article

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.