201621123037 Java programming 10th Week of study summary

Source: Internet
Author: User
Tags finally block throw exception

Job 10-exception

tags (space delimited): Java

1. Study summary 1.1 This week summarize anomalies in the way you like (mind mapping or other).

2. Written work

This PTA job problem set anomaly

1. Common exceptions

Combined Topic 7-1 Answer

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 often occur:
such as unreasonable call, easy to produce a null pointer, jumping nullpointerexception error;
When the type of input and the type of definition are different, jumping numberformatexception error;
When casting for a type, sometimes it jumps classcastexception error;
For arrays, the most common is the cross-border problem of arrays.

These exceptions belong to unchecked Exception, which do not need to be captured, only checked Exception must be captured.

Avoid:
For these null pointers can be judged in advance whether null, array out of bounds can also be added to judge the statement to prevent,
However, you can then use the Try-catch statement to capture the stability of the exception-enhanced code.

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

For:

Exceptions such as Error, RuntimeException, and its subclasses are checked Exception, and such exceptions need to be captured.

When checked exception throws an exception, it needs to be Try-catch block to catch and handle the exception, or for some methods, add
throws keyword to indicate that an exception may be thrown and then processed against the thrown exception.

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?

For:

try {    String x = sc.next();    list[i]=Integer.parseInt(x);}catch(Exception e) {    System.out.println(e);    i--;}   

This problem is for non-integer strings, throw exception information, after catching with catch, output the exception information. It is important to note that, due to filling the entire array, the exception input value is empty , "i--" to complete the topic requirements.

3. Throw and throws

Topic 7-3
Read Integer.parsetint source code

3.1 Integer.parsetint There is a lot of code thrown out of the exception at the outset, what is the benefit of this practice?
  Source code: public static int parseint (String s) throws NumberFormatException {return parseint (s,10);} The string parameter is parsed as a signed decimal integer. The character in the string must be a decimal number, except for the negative numbers represented by the minus sign '-' in the ASCII character. 
Source code: public static int parseint (String s, int radix) throws numberformatexception{/* * Warning:this met Hod may 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 = = '-') {negative = 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 = Character.di            Git (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;}

In the source code throws the numberformatexception exception, throws the exception the judgment mainly is:
S is null, Radix is less than 2, Radix is greater than 36, the first character is neither "-" nor "+" and other exceptions.

In the experimental question, the judgment in the Arrayutils class is also modeled as the above source code to throw, and with the reason of the exception, to provide information to the caller.

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:

The illegalargumentexception exception is thrown and the cause of the exception is also passed, indicating whether the begin/end is a cross-border problem or a relative-size error problem.

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:

The use of throwing exceptions represents a running error, not only the type of error can be reported, but also specific to the cause of the throw error, to the user greater convenience. In addition, if you set the return value according to the previous C language, it will return the result correctly, and return-1 if the error is not rigorous. Because when the return result is-1, the Code of the program will judge it according to the error code, and the rigor of the whole code will be greatly compromised.

4.2 If the inner code of a method throws an exception of type RuntimeException, does the method declaration use the throws keyword, and if the exception that is thrown by the method is declared using the throws keyword, what benefit can it bring us?

For:

You can throw exception benefits with the throws keyword without using the throws keyword:
When an exception does not want to be handled in the method with Try-catch, the exception can be thrown to other classes or methods to handle, at which point the throws is used. And the throw and throws should be paired (except that runtimeexception,runtimeexception can be thrown without the throws declaration exception).

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:

Just like 6-1, where there are multiple errors, you need to be aware of the existence of an inherited relationship when capturing.
the exception handling of the parent class must be placed after the subclass, otherwise the handling of the parent exception will be captured before the subclass. In the title RuntimeException is a subclass of exception, if the exception is placed before the subclass, it is first captured by 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?

For:
Try-catch that are caught unexpectedly in Java8 can automatically close objects opened in a try expression without the developer having to manually close them.

Such as:

Not required:

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 cannot be found, you need to prompt the user not to find the file xxx, retype the file name, and then try to open it again. If it is another exception, prompt to open or read the file failed!.

Note 1: There are several methods inside that can throw an exception.
Feature 2: You need to add a finally close file. Regardless of whether the above code produces an exception, always be prompted to close the file ing. If closing the file fails, the prompt to close the file failed!

For:

one of the above exceptions, change the following to dismiss the error :

    • Need to throw FileNotFoundException exception, so add throws FileNotFoundException.
    • The available () method and the Read () method all need to throw ioexception exceptions, so you need to add throws IOException.
    • FileNotFoundException is a subclass of IOException, so you only need to add throws IOException to solve it.

Change the post code as required:

Import Java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.ioexception;import Java.util.arrays;import Java.util.scanner;public class Boke5_1 {public static void main (string[] args) throws Ioexcept        Ion {byte[] content = null;        Scanner sc = new Scanner (system.in);        FileInputStream FIS =null;        String str = Sc.next ();            while (true) {try {fis = new fileinputstream (str);                FIS = new FileInputStream ("D\testfis.txt"); int bytesavailabe = fis.available ();//Gets the number of bytes available for the file if (bytesavailabe>0) {content = new byt e[bytesavailabe];//creates an array fis.read (content) that can hold the file size;//reads the contents of the file into an array} SYSTEM.OUT.P Rintln (arrays.tostring (content));//print array contents}catch (FileNotFoundException e) {System.out.println ("                Cannot find the Testfis.txt file, please re-enter the filename ");                            str = Sc.next (); } catch(IOException e)                {System.out.println ("failed to open or read file!");            System.exit (0);            }finally {fis.close (); }        }        }}

Operation Result:

6.2 Combining the title set 6-2 code, what kind of action to put in the finally block? Why? What do I need to be aware of when closing resources using finally?

For:
6-2 code, the close () release resource method is placed in the finally block.
Because finally it maintains the internal state of the object and can clean up the role of non-memory resources. Especially in the case of closing the database connection, if you put the close () method of the database connection in the Finally, it will greatly reduce the chance of the program error. And finally also plays a best complementary role.

Using the finally close resource requires attention:

    • The trap of the finally block
源代码:public class Test{      public static void main(String[]args){          FileOutputStream fos=null;          try{               // do something...              System.out.println("打开资源");              System.exit(0);          }finally{              if(fos!=null){                  try{                      fos.close();                  }catch(Exception){                      e.printStackTrace();                  }              }              System.out.println("关闭资源");          }      }   }  

Attention:
"Close resource" is not output because the System.exit (0) in the try block; The current thread is stopped, and the finally block cannot execute a thread that has stopped.

    • Finally block and method return values

public class Test { public static void main(String[] args) { int a = test(); System.out.println(a); } private static int test() { int count = 5; try { System.out.println("try"); return count + 2; // 不执行 } finally { System.out.println("finally"); return -1; // 执行 } } }

Attention:
When there are both return statements and finlly in the try block, the system does not immediately execute the return in the try block, but executes the program in the finally.
If there is a return statement in the finally block, then the REUTRN statement in finally is executed, and then the program ends without executing the return in the try Block

 public class Test {      public static void main(String[] args) {          int a = test();          System.out.println(a);      }        private static int test() {          int count = 5;          try {              throw new RuntimeException("测试异常");  //不执行          } finally {              System.out.println("finally");               return count;          }      }  }  

Attention:
If there is a return statement in the finally block, the program does not actually throw an exception, but returns the return statement after executing the finally block directly.

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

For:

Import Java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.ioexception;import Java.util.arrays;import Java.util.scanner;public class Boke5_1 {public static void main (string[] args) throws Ioexcept        Ion {byte[] content = null;        Scanner sc = new Scanner (system.in);        String str = Sc.next (); while (true) {try (FileInputStream fis = new FileInputStream (str)) {int Bytesavailabe = Fis.avai Lable ();//Gets the number of bytes available for the file if (bytesavailabe>0) {content = new byte[bytesavailabe];//Creates a file size that can fit The array fis.read (content);//Read the contents of the file into the array} System.out.println (Arrays.tostring (conte                 NT));//print array contents}catch (FileNotFoundException e) {System.out.println ("Cannot find Testfis.txt file, re-enter filename");            str = Sc.next ();                } catch (IOException e) {System.out.println ("failed to open or read file!");           System.exit (0); }        }}} 

Operating results (IBID.):

Benefits:

    • The finally block is missing, which simplifies the code refinement.
    • Instead of writing a finally block, system Auto-shutdown allows developers to write without thinking about resource shutdowns, eliminating the risk of code that might occur in development.
7. Object-oriented design job-Library management system (group completion, no more than 3 students per group)

Log in to lib.jmu.edu.cn to 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?

For:
Users include 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.

Students, teachers:

    • Landing
    • Registered
    • Find a book
    • Borrowing books
    • Return books
    • Check current borrowing information
    • Loss

Administrator:

    • Landing
    • Add New Books
    • An old book under the shelf
    • Modify book information
    • Find the whereabouts of a book
    • Reserve books in the query library
7.3 Main class design and class diagram of the system (available)
    • Main design:

User classes [users]: storing user information

Property

private String Name     //用户名private String Account  //账号private String Password //密码static ArrayList<User> user = new ArrayList()   //用于存储每个用户的信息

Method

BorrowBook  //借阅书籍SearchBook  //查找书籍ReturnBook  //归还书籍Show   //查询当前借阅信息

Administrator class [manager]: Administrator Management

Property

private String Name     //用户名private String Account  //账号private String Password //密码static ArrayList<User> Manager = new ArrayList()   //用于存储每个用户的信息

Method

AddBook //增加新书籍DelBook //下架旧书籍FindInformation     //查询书籍去向ChangeInformation   //修改图书信息remainBook  //查询库中预留书籍

Books [Book]

Property

private String Name     //书名private String AuthorName  //作者private int num    //数量static ArrayList<User> books = new ArrayList()   //用于存储书籍条目
    • Class Diagram:

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

For:
During the operation of the user, a dynamic array is used to store the book information, and when the system exits, all the information is written to the file. Presumably so, the specific follow-up team is written and then changed as needed.

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)
For:

    • Chestnut No. 1th:

An error is generated when you enter an ordinal in the menu bar:

The loop is used for repeated input until the input is correctly read in:

Now use the exception class-optimized key code:

try {                x=sc.nextInt();                if(x<0|x>1)                    throw new InputMismatchException("plese input agian:(input在0-1之间)");                 else                    break;            }catch(InputMismatchException e){                 System.out.println(e);                x=sc.nextInt();            }

Operating effect:

    • Chestnut No. 2nd:
      The product information of the shopping cart system is written to the file and then read, the file may be read with an empty exception, and IOException will appear when the file is closed.

Key code:

try {           fils= new FileInputStream(name);            ObjectInputStream objIn=new ObjectInputStream(fils);            temp=(Object[]) objIn.readObject();            objIn.close();                    } catch (IOException e) {            System.out.println("read object failed");                    } catch (ClassNotFoundException e) {            System.out.println(e);        }        finally{            if(fils!=null){                 try {                        fils.close();                    } catch (IOException e) {                        System.out.println(e);                    }        }        }
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
1 0 0 0 0
2 0 0 0 0
3 0 0 0 0
4 0 0 0 0
5 1167 1167 26 26
6 1830 36V 32 6
7 2282 452 45 13
8 2446 164 48 3
9 2774 328 56 8
10 3313 539 65 9
11 3726 413 75 10

201621123037 Java programming 10th Week of study summary

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.