Java basic self-study notes-Chapter 12: Exception Handling and Text I/O

Chapter 12: Exception Handling and Text I/O

1. Overview of exception handling

1. Function
Exception handling allows the program to deal with unexpected situations and continue normal operation

2. In Java, runtime errors are treated as exceptions, and exceptions are an object

3. The exception is thrown from the method, the caller of the method catches and handles the exception

try{
    
    
//正常情况下的运行情况
}
catch(type ex){
    
    //type:捕获的异常类型  ex:catch块的参数
//处理异常
}

2. Exception type

1. System error
Insert picture description here

2. Exceptions are objects, and objects are defined by classes. The root class of the exception is java.long.Throwable.
Insert picture description here
You can also create your own exception class by inheriting the Exception class or the subclass of Exception

3. Common exceptions

abnormal Description
ArrayIndexOutOfBountsException Array out of bounds
InputMisMatchException When entering an integer, enter it as a floating point number
ArthmeticException 0 as the divisor (a floating-point number divided by 0 will not produce an exception )
IllegalArgamentException Illegal or inappropriate parameters passed to the method

Note that the
following examples will not throw exceptions, but will overflow

long l=Long.MAX_VALUE+1;//-9223372036854775808

4. Declare and catch exceptions.
Declaration keyword: throws
declare multiple exceptions separated by commas.
Throw keyword: throw

public static void method() throws Exception()

The following is an example of a declaration catching exception

	public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
		Scanner in = new Scanner(System.in);
		int x = in.nextInt();
		int y = in.nextInt();
		try {
    
    
			System.out.println(devide(x, y));//正常情况下运行
		} catch (ArithmeticException e) {
    
    //捕获异常
			System.out.println(e.toString());//处理异常
		}
	}

	public static int devide(int x, int y) {
    
    //此处异常为运行时异常,故不需要显式声明
		if (y == 0) {
    
    
			throw new ArithmeticException("0不能作除数");//抛出ArithmeticException异常
		} else {
    
    
			return x / y;
		}
	}
	//输入与返回结果:
	//3
    //0
    //java.lang.ArithmeticException: 0不能作除数

Three. Exception handling

1. If the exception is not declared in the parent class, then it cannot be inherited in the subclass to declare the exception

2. If the exception is not caught in the current method, it will be passed to the caller of the method. This process is repeated until the exception is caught or passed to the main method.

3. A compilation error will occur before the catch block of the parent class appears before the catch block of the subclass

try{
    
    }
catch(Exception e){
    
    }
catch(IOException e){
    
    }//错误的顺序

4. Multi-catch exception in JDK7

catch(Exception1|Exception2|Exception3|……)
try{
    
    
method();//如果此方法抛出异常而没有处理,则不会执行下面的语句
System.out.println("hello");
}

5. When no exception occurs, the try-catch block will not cause additional system overhead

6. Finally clause
Regardless of whether an exception occurs, the finally clause will always be executed

Even if there is a return statement before the final clause, the finally clause will still be executed

7. If an exception handler cannot handle an exception or just let the caller notice the exception, then rethrow the exception

8. Create a custom exception class
Exception includes four construction methods, the following are two of them

Exception();//没有消息的异常
Exception(message:String);//有消息的异常

Four.File class

The File class contains methods for obtaining file/directory attributes, as well as for renaming and deleting files. It does not include methods for reading and writing file contents.

Building a File instance does not create a file on the machine, regardless of whether the file exists, you can create a File instance

File file = new File("c:\\z下载\\files\\test\\Demo.txt");
File file = new File("c:/z下载/files/test/Demo.txt");
//使用/或者\\都可以

The methods in the File class will not be introduced in detail, they can be found online.

Five. File input and output

Use the Scanner class to read data from the text, and use the PrintWriter class to write data from the text

java.io.PrinterWriter can create files and write data

The stream must be closed with close(), otherwise the data cannot be saved to the file

You can use try-with-source in jdk7 to prevent forgetting to close the stream

	public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
		File file = new File("c:\\z下载\\files\\test\\notexist.txt");//创建File对象
		try (PrintWriter printWriter = new PrintWriter(file)) {
    
    
			for (int i = 0; i < 10; i++) {
    
    
				printWriter.print(i);//将数据写入文件
			}

		} catch (FileNotFoundException e) {
    
    
			e.printStackTrace();
		}

	}

Insert picture description here
In order to create Scanne to read data from a file, an instance must be created using the construction method new File(fileName).

		File file = new File("c:\\z下载\\files\\test\\notexist.txt");
		try (Scanner input = new Scanner(file)) {
    
    
			while (input.hasNext()) {
    
    
				System.out.print(input.nextInt());
			}
		} catch (FileNotFoundException e) {
    
    
			e.printStackTrace();
		}

Read data from the web

		File file = new File("c:\\z下载\\files\\test\\notexist2.txt");
		try {
    
    
			URL url = new URL("http://www.baidu.com/index.html");

			try (Scanner in = new Scanner(url.openStream()); // 打开流
					PrintWriter printWriter = new PrintWriter(file)) {
    
    
				while (in.hasNext()) {
    
    
					printWriter.print(in.nextLine());//写入文件
				}
			}

		} catch (MalformedURLException e1) {
    
    // MalformedURLException 地址输入错误异常
			e1.printStackTrace();
		}

Insert picture description here
note

  • If you need to repeat input, write in.nextLine() in catch to discard the current line and wrap
  • The class is responsible for throwing exceptions, and the class that calls this method is responsible for capturing and processing

Custom exception steps

  • Inherit the subclass of Exception or Exception
  • Call sper(s) on demand;
  • Declare and throw the exception class just defined in another class
  • Catch and handle exceptions in the test class

Six. Summary

Through the study of this chapter, I know the basic knowledge of Java exceptions and handling, know a lot of exceptions and their causes, and learn to use the File class to create text objects, understand the input and output of text, and obtain information from the Internet .

Come on! Chapter 13 To Be More...

Guess you like

Origin blog.csdn.net/weixin_42563224/article/details/104364602