1. The concept of exception
_Someone once said, "30% of the code in a program project can do something, and the remaining 70% of the code is checking for exceptions, adding constraints...". Why?
- A function module written by a programmer may not work as you like. People's unreliability often leads to the occurrence of Murphy's Law. If you write a four-rule operation, but the user just inputs a divisor equal to 0.
- Some drawbacks in system resources prevent the programmer's code from working properly. If you read a file, it may not exist, or it may be empty, but your program requires that the file not be empty. Or when you run the code but the disk, memory, CPU of the system are saturated, and so on...
_For these unexpected events that affect the normal operation of the program, we call them Exceptions;
2. The calf knife - the first exception
package cn.rowyet.J0004Exception; public class C0001FirstExcept { private String str; public static void main(String[] args) throws Exception { int a=0; int b=1; System.out.println(b/a); } }
_The above code is one of the best understandable exceptions. My primary and secondary school teacher taught us that the divisor can't be 0, or it can't be divided endlessly. So in Java code, if there is a divisor of 0 code, there will be an exception in Figure 2.1, then how to solve the exception? And listen to the following.
3. Classification of anomalies
_As shown in Figure 3.1, Java classifies exceptions according to the object-oriented concept. All the root classes of exceptions are java. Lang.Throwable, java. Is it the only exception that lang.Throwable derives two subclasses, Error and Exception, and Exception derives CheckedException and RuntimeException? Of course not, according to the inheritance characteristics, in principle, there are still unlimited anomalous classes of descendants and grandchildren in the follow-up. This is an endless list. The blogger will start to talk about these basic classes, and you can contradict each other in the following one.
3.1 Error
_Error: refers to a serious problem that the program cannot handle. One of the most common problems that Java may encounter is OutOfMemoryError, which is an error when the JVM virtual machine needs insufficient memory. This will generally cause the JVM to stop working. The solution is to reduce the available memory of the JVM or increase the memory required of the JVM. Figure 3.2 is Error's API.
_Note: Error has little to do with your program, is an error in JVM, but it is not entirely okay. Overwritten programs may also lead to resource abuse and Error;
3.2 Exception
Exception is an exception that programmers can handle. Exception classes are the parent of all exception classes. RuntimeException (runtime exception) and CheckedException (checked exception, also known as compile-time exception) are derived. In other words, Java exceptions are usually classified as runtime exception and compile exception.
3.2.1 RuntimeException
RuntimeException, as its name implies, is an exception type derived from the RuntimeException class, such as NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException, Arithmetic Exception, and so on. Explicit declaration or capture can have a significant impact on program readability and efficiency. Therefore, they are automatically detected by the system and handed over to the default exception handler, which users do not have to handle.
_Such exceptions are usually caused by programming errors, so when writing a program, it is not necessary to use exception handling mechanisms to handle such exceptions. It is often necessary to avoid these exceptions by adding "logical processing". Then the code goes to battle.
- ArithmeticException (operation condition exception)
Example code:
public class C0001FirstExcept { public static void main(String[] args) throws Exception { int a=0; int b=1; System.out.println(b/a); //Operational condition exception, division 0 triggers exception } }
_Running results:
_Solution:
public class C0001FirstExcept { public static void main(String[] args) throws Exception { int a=0; int b=1; if (a!=0) { //Add logical conditions to avoid exceptions System.out.println(b/a); } } }
- NullPointerException (null pointer exception)
Example code:
public class C0001FirstExcept { public static void main(String[] args) throws Exception { String str=null; System.out.println(str.charAt(2)); //Null pointer } }
_Running results:
_Solution:
public class C0001FirstExcept { public static void main(String[] args) throws Exception { String str=null; if (str!=null) { //Add logical judgment System.out.println(str.charAt(2)); } } }
- ClassCastException (type conversion exception)
Example code:
public class C0001FirstExcept { public static void main(String[] args) throws Exception { Animals dog=new Dog(); Cat cat=(Cat) dog; //Type Conversion } } class Animals { } class Dog extends Animals { } class Cat extends Animals { }
_Running results:
_Solution:
public class C0001FirstExcept { public static void main(String[] args) throws Exception { Animals dog=new Dog(); Cat cat=(Cat) dog; //Type Conversion if (dog instanceof Cat) { //Additive Logical Discrimination Cat cat=(Cat) dog; } } } class Animals { } class Dog extends Animals { } class Cat extends Animals { }
- ArrayIndexOutOfBoundsException (Array Cross-Border Exception)
Example code:
public class C0001FirstExcept { public static void main(String[] args) throws Exception { int[] intA=new int[5]; System.out.println(intA[5]); } }
_Running results:
_Solution:
public class C0001FirstExcept { private String str; public static void main(String[] args) throws Exception { int[] intA=new int[5]; a=5; if (a<intA.length) { System.out.println(intA[a]); } } }
- NumberFormatException (data format exception)
Example code:
public class C0001FirstExcept { public static void main(String[] args) throws Exception { String str2="123456hij"; System.out.println(Integer.parseInt(str2)); } }
_Running results:
_Solution:
import java.util.regex.Matcher; import java.util.regex.Pattern; public class C0001FirstExcept { public static void main(String[] args) throws Exception { String str2="123456hij"; Pattern p=Pattern.compile("^\\d+$"); //Regular expressions, beginning and ending with numbers Matcher m=p.matcher(str2); //String can only be regular if (m.matches()) { System.out.println(Integer.parseInt(str2)); } } }
3.2.2 CheckedException
_Those exceptions that are not RuntimeException s are collectively referred to as Checked Exception s (compiled exceptions), such as IOException, SQLException s, and user-defined Exceptions. Such exceptions must be handled at compilation time, otherwise they cannot be compiled, i.e. a red-line Exception will appear in Figure 3.8;
_How to solve it generally requires the handling of the anomalies in the following Chapter IV.
4. Handling Exceptions
4.1 Catch exception try...catch...finally
package cn.rowyet.J0004Exception; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class C0003TryCatch { public static void main(String[] args) { FileReader reader=null; try { reader=new FileReader("src/test.txt"); //The first exception file may not exist, corresponding to the first catch char read = (char)reader.read(); // Second exception, character may be empty char read2 = (char)reader.read(); System.out.println(read+read2); } catch (FileNotFoundException e) { //The exception type of the first catch is less than or equal to the subsequent catch exception e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { //finally is bound to execute try { if(reader!=null) { reader.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
_Use try-catch-finally as an example of reading a file:
- The try statement specifies a code that is the scope of exception capture and handling. When an exception occurs to any statement during execution, the code that follows it will be skipped, so don't try every sentence.
- A try cannot exist alone. It must be followed by a catch or finally. Note that a catch can have more than one, but a final can only have one.
- Exception classes caught by multiple catches. If these types are different and have inheritance relationships, the parent class has to go down. Otherwise, errors will occur. The principle is simple, because if the largest parent class caught by a catch is in the first, the subclasses from subsequent catches will not work at all.
- Finally is executed in most cases, regardless of the exception, unless you encounter System before finally. Exit (0) or program terminated by power loss, network, etc.
4.2 Declare exception throws
-
When CheckedException is produced, it does not have to be dealt with immediately. You can throw the exception to your superior and throw it all the way to JRE, which is a bit like a shaking pot. JRE finally resists everything.
-
The principle of declaring exceptions in method overrides: When a subclass overrides a parent method, if the parent method has declared exceptions, the scope of exceptions declared by the subclass cannot exceed that declared by the parent.
import java.io.FileInputStream; import java.io.FileNotFoundException; public class C0002CheckedException { public static void main(String[] args) throws FileNotFoundException { FileInputStream fileInputStream=new FileInputStream(""); } }
5. Custom Exceptions
_Key points of customizing exceptions:
-
In the program, you may encounter any standard exception classes provided by JDK that do not adequately describe the problem we want to express, or you may want to add some special exception descriptions, such as Chinese descriptions. In this case, you can create your own exception classes, i.e. custom exception classes, which usually define a set of custom exceptions for the project in the source project.
-
Custom exception classes generally only need to derive a subclass from the Exception class or its subclasses. However, if a custom exception class inherits an Exception class, it will be checked and must be handled. If you don't want to, you can have your custom exception class inherit the runtime exception RuntimeException class.
-
Custom exception classes are traditionally composed of two constructors: one default and the other with detailed information.
-
You don't need to define a new class, you can throw an exception directly with a custom description, just write the item so that it is messy, irregular, and rarely used.
_Case Code:
package cn.rowyet.J0004Exception; public class C0005SelfException { public static void main(String[] args) throws HeightExcept { Person person = new Person(); person.setName("RowYet"); person.setHeight(500.0); //Pass a person over 3 meters and throw an exception } } class HeightExcept extends Exception { public HeightExcept(){}; public HeightExcept(String message){ super(message); } } class Person { private String name; private double height; public String getName() { return name; } public double getHeight() { return height; } public void setName(String name) { this.name = name; } public void setHeight(double height) throws HeightExcept { if(height>300.0) //Judging height, more than 3 meters is abnormal { throw new HeightExcept("A person's height must not exceed 3 meters"); } this.height = height; } }
_Running results:
_Of course, you can throw an exception class directly but customize the content of the exception thrown, but what type you throw follows the usage specifications for that type, the code is as follows;
public class C0005SelfException { public static void main(String[] args) { int b=0; if(b!=0) { System.out.println(1/b); } else { throw new ArithmeticException("Divider cannot be zero"); } } }
_Running results;
6. How to resolve exceptions
_In actual development, exceptions are everyday chores, and the more exceptions you solve, the closer you will be to exemplify God. What should you do when you encounter exceptions?
6.1 Try to solve it yourself
_Get plenty of food and clothes by yourself. The first step is to try to do it yourself, locate the abnormal location, check the cause of the abnormality and see if you can solve it yourself.
6.2 Baidu, Bing, Google
_Baidu, Bing, Google, the three great artifacts, basically common anomalies have been encountered by previous people. For the anomalies that you can not handle, you can go to Baidu, Bing, Google to find related web pages to find ideas.
6.3 Ask fellow gods for help
_Neither of the above two steps can be solved, so you can try to get help from the gods of your peers.
6.4 Don't read, I won't
_Never panic in English at the sight of abnormalities. I can't understand them and avoid asking others. This is not only a responsibility for myself but also a result of disrespect for others.