Abnormal conditions refer to abnormal conditions of the program
Corresponding to the classification of exceptions in java, exceptions in java: Throwable serious problems: Error, we don't handle them. Such problems are generally very serious. For example, memory overflow (OOM) problems: exceptions (exceptions) compile time exceptions: except runtimeexceptions, they are compile time exceptions that must be handled. If they are not handled, the program compilation cannot pass, Cannot run. Runtime Exception: RuntimeException. Generally, we will not deal with the problem itself, because such a problem is caused by the lack of logic in the process of writing code.
If there is a problem with the program, and we do not do any processing, the JVM will eventually make the default processing, and output the name of the exception, the relevant reason, and the information of the problem on the console. At the same time, the program will stop, and the subsequent code will not be executed.
public class ExceptionDemo1 { public static void main(String[] args) { int a = 10; // int b = two 0; int b = 0; System.out.println(a/b); //ArithmeticException // if(b!=0){ // System.out.println(a/b); // } System.out.println(10); } }
How to handle exceptions
1,try...catch...finally 2,throws
try...catch...finally processing format:
try {code that may cause problems}
Catch (exception class name variable name) {for the processing code after the problem}
Finally {as long as the program runs smoothly, the contents in finally will be executed anyway}
Deformation format:
try {code that may cause problems}
Catch (exception class name variable name) {for the processing code after the problem}
matters needing attention:
1. The less code in try, the better
2. catch must have content, even a simple hint
public class ExceptionDemo2 { public static void main(String[] args) { int a = 10; int b = 0; try{ System.out.println(a/b); }catch (ArithmeticException e){ System.out.println("Divisor is 0.. . . "); } System.out.println("over"); } }
Methods of dealing with different exceptions
1. Handle an exception
2. Handle two or more exceptions
1) Write a try for each exception catch
2) Write a try and multiple catch es
try {code that may cause problems}
Catch (exception class name 1, variable 1) {handling scheme for exception 1}
Catch (exception class name 2, variable 2) {handling scheme for exception 2}
Precautions when using the second scheme to handle multiple exceptions:
1. catch can only match the corresponding exception, and can only match one exception
2. It doesn't matter the abnormal order of the horizontal relationship. If there is a parent-child inheritance relationship, the parent class must be placed last
3. If there is an error in try, the following code in try will not be executed, and it will match the exception in catch, match the post execution solution, and the following code will execute normally
4. The exception class name in catch should be as clear as possible and should not be handled with large exceptions
public class ExceptionDemo3 { public static void main(String[] args) { // fun(); // fun1(); fun2(); } public static void fun2(){ int a = 10; int b = 5; int[] arr ={1,2,3}; try { System.out.println(a/b); //When you come here, you will report an error. The code behind try will not continue to execute, but directly match the exception in catch System.out.println(arr[4]); }catch (ArrayIndexOutOfBoundsException a1){// System.out.println("Divisor is 0.. . "); }catch (ArithmeticException a2){ System.out.println("Array subscript index out of bounds...."); } System.out.println("over3"); } public static void fun1(){ int a = 10; int b = 0; try{ System.out.println(a/b); }catch (ArithmeticException e){ System.out.println("Divisor is 0.. . . "); } System.out.println("over"); System.out.println("=============================="); int[] arr ={1,2,3}; try { System.out.println(arr[4]); //ArrayIndexOutOfBoundsException }catch (ArrayIndexOutOfBoundsException q){ System.out.println("Array subscript out of bounds.."); } System.out.println("over2"); } public static void fun(){ int a = 10; int b = 0; try{ System.out.println(a/b); }catch (ArithmeticException e){ System.out.println("Divisor is 0.. . . "); } System.out.println("over"); } }
Methods of handling multiple exceptions after JDK1, 7:
try
{potentially problematic code}
catch(ArrayIndexOutOfBoundsException | ArithmeticException | ...)
{solutions to problems}
matters needing attention:
1. The processing method is consistent. Although this method is concise, it is not good enough. Only one solution is given for exceptions of multiple data types
2. In this way, catch can only write exception classes of horizontal relationship!!!
public class ExceptionDemo4 { public static void main(String[] args) { fun(); } public static void fun() { int a = 10; int b = 5; int[] arr = {1, 2, 3}; // try { // System.out.println(a/b); // When you come here, you will report an error. The code behind try will not continue to execute, but directly match the exception in catch // System.out.println(arr[4]); // }catch (ArrayIndexOutOfBoundsException a1){// // System.out.println("divisor is 0."); // }catch (ArithmeticException a2){ // System.out.println("array subscript index out of bounds..."); // } try { System.out.println(a / b); System.out.println(arr[4]); }catch (ArrayIndexOutOfBoundsException|ArithmeticException e){ System.out.println("Something went wrong...."); } System.out.println("over3"); } }
The difference between compile time exception and runtime exception:
Compile time exceptions: Java programs must be handled to display, otherwise the program will have errors and cannot be compiled and run. Run time exceptions: generally, do not handle and modify the code logic, or do the same as compile time exceptions
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class ExceptionDemo5 { public static void main(String[] args) { //Date conversion String s = "2022-02-16 15"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try{ Date date = sdf.parse(s); System.out.println(date); }catch (ParseException e){ System.out.println("Date conversion exception"); } System.out.println("over"); } }
getMessage() gets the exception information and returns a string.
toString() gets the exception class name and exception information, and returns a string.
Return the exception class name + ":" + getLocalizedMessage()
getLocalizedMessage() calls getMessage() internally by default
printStackTrace()
Get the exception class name and exception information, as well as the location of the exception in the program. The return value is void.
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class ExceptionDemo6 {public static void main(String[] args) { //Date conversion String s = "2022-02-16 15"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { Date date = sdf.parse(s); System.out.println(date); } catch (ParseException e) { //ParseException e = new ParseException(); // String message = e.getMessage(); // System.out.println(message); //Unparseable date: "2022-02-16 15" // String s1 = e.toString(); // System.out.println(s1); //java.text.ParseException: Unparseable date: "2022-02-16 15" e.printStackTrace(); } System.out.println("over"); } }
throws
Sometimes we can handle exceptions, but sometimes we don't have permission to handle an exception. If we can't handle it, we don't handle it at all. However, in order to solve this problem and let the program continue to execute, Java provides another exception handling scheme: throws throw
Statement definition format:
throws exception class name
be careful:
1. This format must follow the method's curly braces and before the curly braces.
2. Try not to throw on the main method
Summary:
1. An exception is thrown during compilation, which must be handled by the caller in the future
2. Run time exceptions are thrown, and future calls still need to be processed
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class ExceptionDemo7 { public static void main(String[] args) throws ParseException { System.out.println("What a nice day today"); // try { // fun(); // }catch (ParseException p){ // p.printStackTrace(); // } // fun(); try { fun2(); }catch (ArithmeticException e){ e.printStackTrace(); } System.out.println("You can go for an outing"); } public static void fun2() throws ArithmeticException{ int a = 10; int b = 0; System.out.println(a/b); } public static void fun() throws ParseException { //Date conversion String s = "2022-02-16 15"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = sdf.parse(s); System.out.println(date); } }
throw:
When a situation occurs inside the function method that the program cannot continue to run and needs to jump, throw the exception object with throw.
be careful:
At this time, throw is used to throw the object of the exception class. The difference between throws and throw:
throws
Used after the method declaration, followed by the exception class name
It can be separated from multiple exception class names by commas, indicating that exceptions are thrown and handled by the caller of the method
throws indicates a possibility of exceptions that do not necessarily occur
throw
Used in the method body, followed by the exception object name
Only one exception object name can be thrown
It means that an exception is thrown. If it is handled by the statement in the method body, throw throws an exception, and execution of throw must throw an exception
Story understanding throws and throw:
Join you. You are a happy little miner. One day you are digging, digging, and digging out a bomb (anomaly) left over from World War II. What should you do? It certainly can't be detonated directly in the mine (it can't be handled directly), so it should be passed out (throw exception object). Then you take the bomb to the mine buckle and find that the place dug by your team is the gathering place of bombs during World War II, so it is natural to dig the bomb. Many miners dig it and pass it out (throws, which means multiple exceptions can be thrown at one time). To whom? It is passed to the person in charge of the mine (calling) for processing. Everyone dug up the bomb. In order to distinguish, everyone has the right to name their own bomb (throw can throw a custom exception object).
import java.text.ParseException; public class ExceptionDemo8 { public static void main(String[] args) { try { fun(); }catch (ArithmeticException e){ e.printStackTrace(); }catch (ParseException p){ p.printStackTrace(); } System.out.println("over"); } public static void fun() throws ArithmeticException, ParseException { int a = 10; int b = 0; if(b==0){ System.out.println("hello"); throw new ArithmeticException(); }else { System.out.println(a/b); } } }
The difference between final,finally and finalize
final:
The final meaning can modify classes, member variables and member methods
Decorated class: class cannot be inherited
Decorated member variable: variable becomes constant
Decorated member method: method cannot be overridden
finally:
Is an exception handling try catch.. The finally part is generally used to release resources. Under normal circumstances, it will be executed unless the program stops before finally.
finalize: it is a method in the Object class. It is used for garbage collection. There is no stack reference to the space in the heap memory, but we are not sure when to recycle‘ If there is a return statement in catch, will the finally code still be executed? Will it be executed? If so, will it be before or after return. Execute between.
public class ExceptionDemo9 { public static void main(String[] args) { System.out.println(getInt()); // 30 } public static int getInt() { int a = 10; try { System.out.println(a / 0); a = 20; } catch (ArithmeticException e) { a = 30; return a; // At this point, a return path a=30 has been generated; } finally { a = 40; System.out.println(a); // return a; } return a; } }
finally:
The finally controlled statement body will eventually be executed, except for special cases. Special cases: the JVM exits before executing the finally controlled statement body. Format: try catch... finally
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class FinallyDemo1 { public static void main(String[] args) { //Date conversion String s = "2022-02-16 16:"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = null; try { date = sdf.parse(s); } catch (ParseException e) { e.printStackTrace(); System.exit(0); //Stop the program } finally { //In general, what is written in finally is for //IO operations and database operations are often encountered System.out.println("The code here will be executed!"); } System.out.println(date); } }
File:
Abstract representation of files and paths
Construction method:
public File(String pathname)
Create a new File instance with the given pathname. If the given string is an empty string, the result is an empty abstract pathname.
public File(String parent, String child)
Create a new File instance from the parent pathname string and the child pathname string.
public File(File parent, String child)
Create a new File instance from the parent path Abstract name and the child path string name.
public class FileDemo1 { public static void main(String[] args) { //public File(String pathname) gets a File object according to a path //F:\a.txt is encapsulated into a File object File file = new File("F:\\a.txt"); System.out.println(file); //public File(String parent,String child) //Parent path: F:\demo //Sub path: b.txt File file1 = new File("F:\\demo", "b.txt"); System.out.println(file1); //public File(File parent,String child) //Parent path: F:\demo //Sub path: b.txt File file2 = new File("F:\\demo"); File file3 = new File(file2, "b.txt"); System.out.println(file3); //D:\a.txt //D:\demo\b.txt //D:\demo\c.txt } }
Create function:
public boolearn createNewFile()
public boolean mkdir()
public boolean mkdirs()
public class FileDemo2 { public static void main(String[] args) { //Requirement: I want to create a folder demo2 under disk F //Encapsulated as a File object, it doesn't need whether the File or directory already exists. It just abstracts a path and represents it with File //In the future, you can use some methods in the File class to create or delete File file = new File("F:\\demo2"); //public boolean mkdir() creates a directory named by this abstract pathname. If the target folder already exists, it will not be created and returns false System.out.println(file.mkdir()); //public boolean createNewFile() atomically creates a new empty file named by the abstract pathname if and only if the file with that name does not yet exist. try { System.out.println(file.createNewFile()); } catch (IOException e) { e.printStackTrace(); } //Requirement 2: I want to create a file b.txt in the demo2 folder under disk F //Encapsulate the target File into a File object File file1 = new File("F:\\demo2\\b.txt"); // try { // System.out.println(file1.createNewFile()); // } catch (IOException e) { // e.printStackTrace(); // } // System.out.println(file1.mkdir()); //public boolean mkdirs() creates multi-level folders File file2 = new File("F:\\demo2\\demo3\\demo4\\demo5"); System.out.println(file2.mkdirs()); //Note 1: to create files in a directory, the premise is that the directory must exist!! File file3 = new File("F:\\demo3\\b.txt"); try { System.out.println(file3.createNewFile()); //The system cannot find the specified path. } catch (IOException e) { e.printStackTrace(); } //Note 2: in the future, you should find out whether you want to create files or folders. It is not necessarily the prince who rides the white horse, but also the Tang monk } }
Delete function:
public boolean delete()
public class FileDemo3 { public static void main(String[] args) throws IOException { File file = new File("F:\\a.txt"); System.out.println(file.delete()); File file1 = new File("a.txt"); System.out.println(file1.createNewFile()); File file2 = new File("aaa\\bbb\\ccc"); System.out.println(file2.mkdirs()); System.out.println(file2.delete()); File file4 = new File("aaa\\bbb"); System.out.println(file4.delete()); //Requirement: I want to delete aaa folder //Note: the directory to be deleted must be empty File file3 = new File("aaa"); System.out.println(file3.delete()); } }
Rename function:
public boolean renameTo(File dest)
public class FileDemo4 { public static void main(String[] args) { File file = new File("E:\\ftm.jpg"); //Now I want to rename it von Timo jpg File file1 = new File("E:\\Feng Timo.jpg"); System.out.println(file.renameTo(file1)); } }
Judgment function:
public boolean isDirectory()
public boolean isFile()
public boolean exists()
public boolean canRead()
public boolean canWrite()
public boolean isHidden()
public class FileDemo5 { public static void main(String[] args) { File file = new File("a.txt"); // File file = new File("b.txt"); //public boolean isDirectory() determines whether it is a folder System.out.println(file.isDirectory()); //public boolean isFile() determines whether it is a file System.out.println(file.isFile()); //public boolean exists() determines whether the target file or folder exists System.out.println(file.exists()); //public boolean canRead() determines whether it is readable System.out.println(file.canRead()); //public boolean canWrite() determines whether it is readable System.out.println(file.canWrite()); //public boolean isHidden() judge whether to hide System.out.println(file.isHidden()); } }
Basic acquisition functions:
public String getAbsolutePath()
public String getPath()
public String getName()
public long length()
public long lastModified()
public class FileDemo6 { public static void main(String[] args) { File file = new File("a.txt"); //public String getAbsolutePath() //Get absolute path, or full path System.out.println(file.getAbsolutePath()); //public String getPath() //Get relative path System.out.println(file.getPath()); //public String getName() //Get name System.out.println(file.getName()); //public long length() //The length obtained is the number of bytes System.out.println(file.length()); //public long lastModified() //1645064059299 accurate to milliseconds //A timestamp is returned System.out.println(file.lastModified()); //java converts timestamp and date //Date(long date) //Allocates a Date object and initializes it to represent the specified number of milliseconds after the standard reference time called "time", that is, January 1, 1970 00:00:00 GMT. Date date = new Date(file.lastModified()); System.out.println(date); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String format = sdf.format(date); System.out.println(format); } }
Advanced access features:
public String[ ] list();
public File[ ] listFile();
import java.io.File; public class FileDemo7 { public static void main(String[] args) { File file = new File("E:\\Digital plus Technology\\15th issue"); //public String[] list() //Gets an array of the names of all files and folders in the specified directory String[] list = file.list(); for (String s : list) { System.out.println(s); } System.out.println("============================"); //public File[] listFiles() //Gets the File object array formed by all files and folders in the specified directory File[] files = file.listFiles(); for (File f : files) { System.out.println(f); } } }
Requirement: judge whether there is a file with jpg suffix under disk D. if so, output the name of this file;
1. Encapsulate the root directory of disk D into an object;
2. Obtain the File file array composed of all files or folders in the directory;
3. Traverse the File array to get each object, and then judge whether it is a File
Yes: continue to judge whether it is jpg suffix
Yes: output name;
No: ignore him;
No: ignore him;
public class FileDemo8 { public static void main(String[] args) { File file = new File("D:\\"); File[] files = file.listFiles(); for(File f : files){ if(f.isFile()){ if(f.getName().endsWith(".jpg")){ System.out.println(f.getName()); } } } } }
Judge whether there are jpg files under disk D. if so, output the file name:
1. First get all the folders, and then when traversing, judge whether it is a file or not jpg suffix, and finally filter out the qualified ones to obtain the name.
2. When acquiring, the acquired data meets the conditions, and we can output it directly.
import java.io.File; import java.io.FilenameFilter; /* Implementation idea and code of file name filter public String[] list(FilenameFilter filter) public File[] listFiles(FilenameFilter filter) */ public class FileDemo9 { public static void main(String[] args) { //Create File object File file = new File("D:\\"); //public String[] list(FilenameFilter filter) String[] list = file.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { // return false; // return true; //Through the test, it is found that whether the files or folders in the directory should be obtained depends on the return value here //true, get and add to the array. If false, don't get and add to the array // System.out.println(dir); // System.out.println(name); File file1 = new File(dir, name); boolean b = file1.isFile(); boolean b1 = name.endsWith(".jpg"); return b && b1; } }); for (String s : list){ System.out.println(s); } } }
Recursion:
Method defines the phenomenon of calling method itself.
Math. Methods such as Max (math. Max (a, b), c) are only the nesting of methods, not the recursive use of methods.
For example: 1. Once upon a time, there was a mountain and a temple in the mountain. There was an old monk in the temple. The old monk was telling a story to the little monk. The content of the story was: Once upon a time, there was a mountain and a temple in the mountain. There was an old monk in the temple. The old monk was telling a story to the little monk. The content of the story was: Once upon a time, there was a mountain and a temple in the mountain. There was an old monk in the temple. The old monk was telling a story to the little monk, The content of the story is: The temple fell and the old monk died.
2. Learning big data -- high paying Employment -- making money -- marrying a daughter-in-law -- giving birth to a baby -- earning tuition fees: learning big data -- high paying Employment -- making money -- marrying a daughter-in-law -- giving birth to a baby -- earning tuition fees: learning big data -- high paying Employment -- making money -- marrying a daughter-in-law -- giving birth to a baby -- earning tuition fees: If you can't marry a daughter-in-law, you can't have a baby.
Precautions for recursion:
1. Recursion must have an exit (end condition), otherwise it will become dead recursion;
2. The number of recursion should not be too many, otherwise it will cause stack memory overflow;
3. The construction method cannot be recursive;
Dead recursion:
public class DiGuiDemo1 { // public DiGuiDemo1(){ // DiGuiDemo1(); // } //Dead recursion public void show(){ show(); } }
Requirements: use code to realize factorial of 5;
5!=5*4*3*2*1
There are two ways:
1. Implemented with for loop;
2. Recursive implementation;
public class DiGuiDemo2 { public static void main(String[] args) { // int i = 1; // for (int x = 2; x <= 5; x++) { // i = i * x; // } // System. out. Factorial of "printi + lnI"; //It is implemented in the form of recursion System.out.println("5 The factorial of is:" + diGui(5)); } /** * Premise of recursive method: * Return value type: int * Parameter list: int i * * Export conditions: * if(i==1){return 1} * * Recursive body logic: * if(i!=1){ * return i*diGui(i-1); * } */ public static int diGui(int i){ if(i==1){ return 1; }else { return i*diGui(i-1); } } }
Case of immortal rabbit:
Suppose there is a pair of rabbits. From the third month of birth, a pair of rabbits will be born every month. After the little rabbit grows to three months, another pair of rabbits will be born. Assuming that all rabbits will not die, ask how many rabbits there are after 20 months;
Array implementation;
Variable implementation;
Recursive implementation;
Law finding: month Logarithm of rabbit First month 1 The second month 1 The third month 2 The fourth month 3 The fifth month 5 The sixth month 8 ... From this courseware, the data of rabbit logarithm is: 1,1,2,3,5,8,13,21,34... law: 1,Starting from the third item, each item is the sum of the first two items 2,Explain that the data of the first two items are known Define two variables as adjacent data 1st adjacent data: a=1,b=1 2nd adjacent data: a=1,b=2 3rd adjacent data: a=2,b=3 4th adjacent data: a=3,b=5 Law: the next adjacent data, a The value of is the last time b The value of, b The value of is the sum of the previous adjacent data a+b */ public class DiGuiDemo3 { public static void main(String[] args) { //Implementation with array int[] arr = new int[20]; arr[0] = 1; arr[1] = 1; // arr[2] = arr[0] + arr[1]; // arr[3] = arr[1] + arr[2]; // //... // arr[19] = arr[17] + arr[18]; for (int i = 2; i < arr.length; i++) { arr[i] = arr[i - 2] + arr[i - 1]; } System.out.println("The number of rabbits after the 20th month is:" + arr[19]); System.out.println("============================="); //Basic variable implementation //For the next adjacent data, the value of a is the value of the previous b, and the value of b is the sum of the previous adjacent data a+b int a = 1; int b = 1; for (int i = 1; i <= 18; i++) { //Define a temporary variable to store the value of the last a int tmp = a; a = b; b = tmp + b; } System.out.println("The number of rabbits after the 20th month is:" + b); System.out.println("============================="); //Recursive form System.out.println("The number of rabbits after the 20th month is:" + Fibonacci(20)); } /** * Return value type: int * Parameter list: int i 20 * <p> * Export conditions: 1 in the first month and 1 in the second month * Recursive condition: starting from the third month, the value of each month is the sum of the first two months */ public static int Fibonacci(int i) { // 4 //The first month is 1, and the second month is also 1 if (i == 1 || i == 2) { return 1; } else { //Starting from the third month, the value of each month is the sum of the first two months return Fibonacci(i - 1) + Fibonacci(i - 2); //Fibonacci(3) +Fibonacci(2) //Fibonacci(2) + Fibonacci(1) + 1 //1 + 1 + 1 //3 } } }
Traverse all file names with specified suffixes in the specified directory:
analysis:
1. Get the File object;
2. Get all the files and folders in the directory to form a File object array;
3. Traverse the array to get each File object;
4. Determine whether this File is a folder
public class DiGuiDemo4 { public static void main(String[] args) { //Encapsulate directories into File objects File file = new File("E:\\Digital plus Technology\\15th issue"); //Recursive implementation getJavaFile(file); } public static void getJavaFile(File file){ //Gets an array of all File objects in the directory File[] files = file.listFiles(); //Traverse the array to get each File object for(File f : files){ //Determine whether it is a folder if(f.isDirectory()){ getJavaFile(f); }else { //Judge whether the file name is in java suffix if(f.getName().endsWith(".java")){ //If yes, output System.out.println(f.getName()); } } } } }
Recursively delete directories with content:
analysis:
1. Get the File object;
2. Get all the files and folders in the directory to form a File object array;
3. Traverse the array to get each File object;
4. Determine whether this File is a folder
Yes: return to step 2
No: delete directly
public class DiGuiDemo5 { public static void main(String[] args) { File file = new File("D:\\IdeaProjects\\bigdata15\\aaa"); deleteFile(file); } public static void deleteFile(File file) { //Get the File object array composed of all files and folders in the directory File[] files = file.listFiles(); if (files != null) { //Traverse the array to get each File object for (File f : files) { //Determine whether the File object is a folder if (f.isDirectory()) { deleteFile(f); } else { System.out.println(f.getName() + "---" + f.delete()); } } System.out.println(file.getName() + "---" + file.delete()); } } }