JavaSE basics-(19) exceptions and input and output

table of Contents

1. Abnormal

1.1 Overview and classification of anomalies

1.2 JVM default handling exception method

1.3 custom exception handling method

1.3.1 try catch to handle arithmetic exceptions

1.3.2 try catch to handle multiple exceptions

1.4 Compile-time exceptions and runtime exceptions

1.5 Common methods of Trowable

1.6throws way to handle exceptions

1.7finally keyword

1.8 About finally interview questions

1.9 Custom Exception

1.10 Precautions for abnormalities

1.11 Abnormal Practice

Two, File class

2.1File overview and common construction methods

2.2 The creation function of the File class

2.3 Rename and delete function of File class

2.4 Judgment function of File class

2.5 Get function of File class

2.6 Specify the file type name in the output drive letter

2.7 File name filter


 

1. Abnormal

1.1 Overview and classification of anomalies

Exceptions are some errors that occur during the running of the java program.

The bottom of the exception is Throwable, which is divided into Error and Exception.

Error generally includes server down or database crash. We only need to focus on Exception. The following figure is a schematic diagram of the structure of some exceptions.

And RuntimeException is a running exception, and it is the key learning content in Exception, which is generally likely to be encountered in our usual programming.

 

1.2 JVM default handling exception method

After the program generates an exception, the exception will be received by the main function. The main function generally has two solutions:

  • Solve the exception by yourself, and then the program continues to run
  • If I don’t have a solution, I will hand it over to the JVM that calls the main function.

The JVM has a default exception handling mechanism, which handles the exception.

And the name of the exception, the information of the exception, and the location of the exception are printed on the console, and the program will stop running at the same time.

For example, we let the divisor be 0 to see what exceptions will be thrown,

public class ExceptionTest {
    public static void main(String[] args) {
        System.out.println(div(1,0));
    }
    public static int div(int a,int b){
        return a/b;
    }
}

 

1.3 custom exception handling method

Two ways of exception handling:

  • a:try+catch+finally
    • try catch
    • try catch finally
    • try finally
  • b:throws

The try catch method is our commonly used method. After the exception is handled by try catch, the program can be executed normally.

Try is used to detect exceptions, catch is to catch exceptions, and finally is to release resources. Let's take a look at how to use it.

1.3.1 try catch to handle arithmetic exceptions

public class ExceptionTest {
    public static void main(String[] args) {
        try{
            System.out.println(div(1,0));
        }catch (ArithmeticException a){//捕获算数异常
            System.out.println("除数为0");
        }
    }
    public static int div(int a,int b){
        return a/b;
    }
}

 

1.3.2 try catch to handle multiple exceptions

        int a=10;
        int b=0;
        int arr[]={1,2,3,4,5};
        try{
            System.out.println(a/b);
            System.out.println(arr[8]);
        }catch (ArithmeticException |ArrayIndexOutOfBoundsException e){
            System.out.println("程序出现异常");
        }

We can also directly catch the underlying Exception of the exception so that it can be directly obtained regardless of which exception it belongs to.

catch (Exception e){
    System.out.println("程序出现异常");
}

 

1.4 Compile-time exceptions and runtime exceptions

Exceptions in Java are divided into two categories, compile-time exceptions and runtime exceptions.

All instances of the RuntimeException class and its subclasses are called runtime exceptions, and other exceptions are compile-time exceptions.

They have the following characteristics:

  • Compilation period exception: Java program must be displayed and processed, otherwise the program will have an error and fail to compile
  • Runtime exceptions: no display processing is required, and it can be handled the same as compile-time exceptions

In general, the exception during compilation is that the program will prompt a red underlined wavy line when it is written. If it is not modified, it will not be able to pass the compilation.

For example, when we are reading a file, if we write a file read statement directly, the program will prompt that there is an exception that the file cannot be found.

It means that the program does not know whether this file can be found before running. If it is not found, the program will have a problem, so we are required to display and handle this exception in advance.

We can solve this problem by writing this operation in the try statement,

Runtime exceptions are more common. They are errors that programmers often make, such as dividing the number by 0, arrays out of bounds, and so on.

 

1.5 Common methods of Trowable

get Message()//获取异常信息,返回字符串
toString()//获取异常类名和异常信息,返回字符串
printStackTrace()//获取异常类名和异常信息,以及异常出现在程序中的位置,返回值void
        try{
            FileInputStream file=new FileInputStream("test.txt");
        }catch (FileNotFoundException fe){
            System.out.println(fe.getMessage());
            System.out.println("----------------------------------------");
            System.out.println(fe.toString());
            System.out.println("----------------------------------------");
            fe.printStackTrace();
        }

 

1.6throws way to handle exceptions

The throws way to handle exceptions is to throw a new exception object (for example, throw new Exception("***")) where the program may go wrong.

It should be noted that if a compile-time exception is thrown, a throws exception object class must be added to the thrown method (for example, throws Exception),

The meaning of this sentence is to throw the exception to the function that calls it. If it is a runtime exception, you do not need to add this sentence to the method.

If throws Exception is also added to the main function, the exception will be thrown to the java virtual machine JVM, and the exception will be handled by the default method.

public class ExceptionTest {
    public static void main(String[] args) throws Exception {
        div(1,0);
    }

    public static int div(int a,int b) throws Exception {
        if(b!=0){
            return a/b;
        }else{
            throw new Exception("除数为0");
        }
    }
}

Careful here may have discovered that in the method we write throw, and in the method we write throws. The main differences between them are as follows:

  • Throws appears at the head of the method function, and throw appears at the function body.
  • Throws represents the possibility of an exception, and it does not necessarily cause an exception; throw means an exception is thrown, and execution of throw must throw an exception object

 

1.7finally keyword

The characteristic of the finally keyword is that the statement controlled by finally will be executed.

Unless the JVM has exited before the finally statement is executed (System.exit(0)),

Finally, it is generally used to release resources and is often seen in IO stream operations and database operations.

        try {
            System.out.println(1/0);
        }catch (Exception e){
            System.out.println("除数为0");
            return;//会在执行return语句之后执行finally控制的语句,然后再彻底结束方法
        }finally {
            System.out.println("finally控制语句");
        }

It can be seen that even if the return statement is executed before finally, the finally controlled statement will still be executed.

When the program executes the return statement ending method, it will first see if there is a finally statement, if there is a finally control statement, it will return directly.

 

1.8 About finally interview questions

1. The difference between final, finally and finalize

  • final is a modifier
    • Can modify the class, the modified class cannot be inherited
    • The method can be modified, and the modified method cannot be overridden
    • Variables can be modified, and the modified variable value cannot be changed
  • Finally is a statement body in try, which cannot be used alone to release resources
  • Finalize is a method in Object, when the garbage collector determines that there is no reference to the object, this method is called by the object's garbage collector

 

2. If there is a return statement in the catch statement, will the finally controlled code still be executed? If it will be executed before return or after return?

Through the example of 1.7, we can know that even if there is a return statement in the catch, the finally controlled code block will still be executed, and the finally statement is executed after the object value returned by return is determined and packaged.

 

1.9 Custom Exception

Although Java has defined many exceptions for us, we still encounter many problems when programming.

For example, we define a student class. When the user enters the name and age when creating a new class, there are constraints on the age input, such as 0 to 120 years old.

At least it cannot be a negative number. If a negative number is given when assigning a student’s age, we hope to throw an exception and output an exception message, telling us that the age input is a negative number.

We can customize an exception, inherit from Exception, if what you want is a runtime exception, then inherit from RuntimeException,

Runtime exceptions do not need to write try and catch statements, and do not need to display the exceptions, so here our custom exceptions are inherited from RuntimeException,

public class ExceptionTest {
    public static void main(String[] args){
        Student stu=new Student();
        stu.setAge(-1);
    }
}

class AgeOutOfBoundsException extends RuntimeException {
    public AgeOutOfBoundsException() {
    }

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

class Student{
    private String name;
    private int age;

    public Student(){}
    public Student(String name,int age){
        this.name=name;
        this.age=age;
    }
    public String getName(){
        return name;
    }
    public int getAge(){
        return age;
    }
    public void setName(String name){
        this.name=name;
    }
    public void setAge(int age) throws AgeOutOfBoundsException {
        if(age>0 && age<120){
            this.age=age;
        }else{
            throw new AgeOutOfBoundsException("年龄超出范围");
        }
    }
}

 

1.10 Precautions for abnormalities

The exception mainly has the following precautions:

  • When the subclass overrides the superclass method, the subclass method must throw the same exception or the subclass of the superclass exception
  • If the parent class throws multiple exceptions, when the subclass overrides the parent class, it can only throw the same exception or a partial subset of multiple exceptions, and cannot throw exceptions that the parent class does not have.
  • If the overridden method does not throw an exception, then the method of the subclass cannot throw an exception. If an exception occurs in the method of the subclass, the subclass can only try to resolve the exception by itself, and cannot throw exceptions.

When using exceptions, you need to pay attention to:

  • If the exception can be resolved inside the function, use the try statement; if the exception cannot be resolved, use throws to throw the exception
  • If you need to continue to run the subsequent program, use try, if you don’t need to continue to run the subsequent code, use throws

 

1.11 Abnormal Practice

Requirement: keyboard input an integer, find the binary form of the integer,

If the entered integer is too large, the user is prompted to enter the integer too large, please enter an integer again,

If the input is a decimal, the user is prompted to input a decimal, please re-enter a whole number,

If other characters are entered, the user is prompted to enter illegal characters, please enter an integer again,

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Scanner;

public class ExceptionPractice {
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        System.out.println("请输入一个整数:");

        while(true){
            String input=scanner.nextLine();//先用字符串存储输入,避免输入不是整数直接报错
            try {
                int num=Integer.parseInt(input);//将字符串转换为整数
                System.out.println(Integer.toBinaryString(num));//将整数转换为二进制形式
                break;
            }catch (Exception e1){
                try{
                    new BigInteger(input);//若能装入BigInteger,则说明不是非法字符和小数
                    System.out.println("录入整数过大,请重新录入一个整数:");
                }catch (Exception e2){
                    try {
                        new BigDecimal(input);//若可以装入BigDecimal,则说明不是非法字符
                        System.out.println("录入的是小数,请重新录入一个整数:");
                    }catch (Exception e3){
                        System.out.println("录入的是非法字符,请重新录入一个整数:");
                    }
                }
            }
        }
    }
}

 

Two, File class

2.1File overview and common construction methods

The File class should be called a path, which is an abstract expression of file and directory path names.

The path is divided into absolute path and relative path. The absolute path is the file path starting from the drive letter.

The relative path refers to the path relative to the project path. For example, we can write the file name directly without adding the path to the file under the current project path.

Let's first learn about several construction methods of File,

File(File parent,String child)//根据parent路径名和child路径名字符串创建一个新File实例
File(String pathname)//根据给定路径名字符串创建一个新File实例
File(String parent,String child)//根据parent路径名字符串和child路径名字符串创建一个新File实例
File(URI uri)//通过给定的URI创建一个新的File实例

Let’s learn the first three below and see how to use them.

        File file1 = new File("data.txt");//相对路径读取文件
        System.out.println(file1.getName());
        File file2 = new File("E:\\1program\\6Java\\JavaBasic\\01.HelloWorld\\src\\data.txt");//绝对路径读取文件
        System.out.println(file2.getName());

        String parentStr="E:\\1program\\6Java\\JavaBasic\\01.HelloWorld\\src";
        String childStr="data.txt";
        File file3 = new File(parentStr,childStr);
        System.out.println(file3.getName());

        File parentFile=new File(parentStr);
        File file4 = new File(parentFile,childStr);
        System.out.println(file4.getName());

You can see that the name of the file is correctly obtained in the three ways.

 

2.2 The creation function of the File class

public boolean createNewFile()//创建文件,如果已经存在则不再创建
public boolean mkdir()//创建文件夹,如果文件夹已存在则不再创建
public boolean mkdirs()//创建文件夹,如果父文件夹也不存在,则会一起创建

Let’s take a look at how to use it,

File file=new File("dataNew.txt");
System.out.println(file.createNewFile());//如果不存在dataNew.txt文件,则创建一个dataNew.txt,否则不创建
File file1=new File("dirNew");
System.out.println(file1.mkdir());

File file2=new File("dirFather\\dirSon");
System.out.println(file2.mkdirs());

If you create a file or folder without writing the absolute path of the drive letter, it will be created under the project path by default.

 

2.3 Rename and delete function of File class

public boolean renameTo(File dest)//把文件重命名为指定的文件路径
public boolean delete()//删除文件或者文件夹

When renaming, if the path name is the same, then the folder is renamed,

If the path names are different, the folder is cut to the target path after the name is changed.

When deleting, the file will not be deleted to the recycle bin, so it cannot be restored after deletion.

If you want to delete a folder, it cannot contain files or folders.

 

2.4 Judgment function of File class

public boolean isDirectory()//判断是否为目录
public boolean isFile()//判断是否为文件
public boolean exists()//判断是否存在
public boolean canRead()//判断是否可读
public boolean canWrite()//判断是否可写
public boolean isHidden()//判断是否隐藏

We can set file readability and writability through methods,

public boolean setReadable(boolean readable)//设置文件可读性(windows系统认为一切文件都是可读的)
public boolean setWriteable(boolean writeable)//设置文件可写性(windows系统可以设置文件不可写)

 

2.5 Get function of File class

public String getAbsolutePath()//获取绝对路径
public String getPath()//获取路径(构造方法中传入的路径)
public String getName()//获取名称
public long length()//获取文件字节的长度,字节数
public long lastModified()//获取最后一次的修改时间,毫秒值
public String[] list()//获取指定目录下的所有文件和文件夹的名称数组
public File[] listFiles()//获取指定目录下的所有文件和文件夹的File数组

 

2.6 Specify the file type name in the output drive letter

import java.io.File;

public class FileTest {
    public static void main(String[] args){
        File dir=new File("F:\\");
        String arr[]=dir.list();
        for (String str : arr) {
            if(str.endsWith(".cpp")) {
                System.out.println(str);
            }
        }
    }
}

The result verification is also correct,

You can also get all files and folders directly, and then judge by getName, both methods can get the correct result.

        File dir=new File("F:\\");
        File subFiles[]=dir.listFiles();
        for (File file : subFiles) {
            if(file.isFile()&&file.getName().endsWith(".cpp")) {
                System.out.println(file.getName());
            }
        }

 

2.7 File name filter

File name filter is to give a filter, and then find files that meet the conditions,

There are mainly the following two filtering methods. The first one gets the string array of the file, and the second one gets the file array.

public String[] list(FilenameFilter filter)
public File[] listFiles(FileFilter filter)

Let’s see how to use it,

        File dir=new File("F:\\");
        String arr[]=dir.list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                File file=new File(dir,name);
                return file.isFile()&&file.getName().endsWith(".cpp");
            }
        });
        for (String str : arr) {
            System.out.println(str);
        }

We see that the file name with the suffix cpp is also output,

 

Guess you like

Origin blog.csdn.net/weixin_39478524/article/details/112794587