Introduce exception
- Exception: refers to the abnormal situation during the execution of the program. If it is not handled, it will eventually lead to the abnormal stop of the JVM.
The exception does not refer to syntax error. If the syntax is wrong, the compilation fails, no bytecode file will be generated, and it cannot run at all
Exception does not mean that the logical code is wrong and the desired result is not obtained. For example, when you sum a and b, you write the case that the divisor of a-b is 0
In Java, different exceptions are represented by different classes. Once an exception occurs, create an object of the exception type and throw it. Then the programmer can catch the exception object and handle it. If the exception object cannot be caught, the exception object will cause the program to terminate.
Anomaly classification
The root class of exception is java.lang.Throwable, which has two subclasses: java.lang.Error and java.lang.Exception. Normally, the exception refers to java.lang.Exception.
Throwable system:
- Error: serious error. An error that cannot be handled can only be avoided in advance, like a terminal disease.
- For example: StackOverflowError, OOM (OutOfMemoryError) Memory Leak.
- Out Of Memory (OOM) refers to the existence of unrecoverable memory in the application system Memory Or used Memory Too much, which eventually makes the program run Memory Greater than the maximum memory available.
- Memory Leak refers to that the heap memory that has been dynamically allocated in the program has not been released or cannot be released due to some reason, resulting in a waste of system memory, resulting in serious consequences such as slow down of program operation and even system crash.
- Exception: indicates an exception. Other general problems caused by programming errors or accidental external factors can be corrected by the programmer through code to make the program continue to run, which must be handled. Like colds and appendicitis.
- For example: null pointer access, trying to read non-existent files, network connection interruption, array subscript out of bounds
Common methods in Throwable:
-
public void printStackTrace(): print the details of the exception.
It includes the type of exception, the reason for the exception, and the location of the exception. printStackTrace must be used in the development and debugging stages.
-
public String getMessage(): get the reason for the exception.
When the prompt is given to the user, the reason for the error will be prompted.
We usually refer to exceptions, because once such exceptions occur, we need to correct the code and repair the program.
Classification of exceptions: check exceptions at compile time or run time?
- Compile time exception: checked exception. At compile time, it will be checked. If the exception is not handled, the compilation fails. (if the file cannot find the exception)
- Runtime exception: runtime exception. During operation, check for exceptions During compilation, the running exception will not be detected by the compiler (no error will be reported). (such as array index out of bounds exception, type conversion exception). Programmers should actively avoid their exceptions instead of using try... catch to handle them, because such exceptions are very common, and using try... catch or throws to handle them may affect the readability and running efficiency of the program.
Common errors and exceptions
VirtualMachineError
The most common ones are: StackOverflowError, OutOfMemoryError
@Test public void test01(){ //StackOverflowError digui(); } public void digui(){ digui(); }
@Test public void test02(){ //OutOfMemoryError //Method 1: int[] arr = new int[Integer.MAX_VALUE]; } @Test public void test03(){ //OutOfMemoryError //Mode 2: StringBuilder s = new StringBuilder(); while(true){ s.append("gec"); } }
Runtime exception
@Test public void test01(){ //NullPointerException int[][] arr = new int[3][]; System.out.println(arr[0].length); } @Test public void test02(){ //ClassCastException Person p = new Man(); Woman w = (Woman) p; } @Test public void test03(){ //ArrayIndexOutOfBoundsException int[] arr = new int[5]; for (int i = 1; i <= 5; i++) { System.out.println(arr[i]); } } @Test public void test04(){ //InputMismatchException Scanner input = new Scanner(System.in); System.out.print("Please enter an integer:"); int num = input.nextInt(); } @Test public void test05(){ int a = 1; int b = 0; //ArithmeticException System.out.println(a/b); }
Compile time exception
@Test public void test06() throws InterruptedException{ Thread.sleep(1000);//Sleep for 1 second } @Test public void test07() throws FileNotFoundException{ FileInputStream fis = new FileInputStream("Java Learning Secrets.txt"); } @Test public void test08() throws SQLException{ Connection conn = DriverManager.getConnection("...."); }
Exception throwing mechanism
First run the following program, which will generate an array index out of bounds exception ArrayIndexOfBoundsException. We use diagrams to analyze the process of anomaly generation.
Tools
public class ArrayTools { // Get the elements of the given array through the given subscript. public static int getElement(int[] arr, int index) { int element = arr[index]; return element; } }
Test class
public class ExceptionDemo { public static void main(String[] args) { int[] arr = { 34, 12, 67 }; int num = ArrayTools.getElement(arr, 4) System.out.println("num=" + num); System.out.println("end!"); } }
Diagram of the above procedure execution process:
Five keywords of Java exception handling: try, catch, finally, throw, throws
Abnormal throw
If an exception occurs during the execution of a java program, an exception class object will be generated, and the exception object will be submitted to the Java runtime system. This process is called throwing an exception. There are two ways to generate exception objects:
- Automatically generated by the virtual machine: during the running process of the program, the virtual machine detects that there is a problem with the program. If the corresponding handler is not found in the current code, an instance object of the corresponding exception class will be automatically created in the background and thrown - automatically thrown
- Manually created by developers: Exception exception = new ClassCastException()—— Creating an exception object without throwing has no impact on the program, just like creating an ordinary object, but once thrown, it will have an impact on the operation of the program.
Let's explain how to throw an exception manually:
For example, when defining a method, the method needs to accept parameters. Then, when calling the method to use the received parameters, first of all, you need to make a legal judgment on the parameter data. If the data is illegal, you should tell the caller. At this time, you can tell the caller by throwing an exception.
In java, a throw keyword is provided, which is used to throw a specified exception object.
The specific operations are as follows:
-
Create an exception object. Encapsulate some prompt information (the information can be written by yourself).
-
You need to inform the caller of this exception object. The keyword throw can inform the caller to pass the exception object to the caller. Throw exception object.
Throw is used in a method to throw an exception object, pass the exception object to the caller, and end the execution of the current method.
Use format:
throw new Exception class name(parameter);
For example:
throw new NullPointerException("To access arr Array does not exist"); throw new ArrayIndexOutOfBoundsException("The index does not exist in the array and is out of range");
The following demonstrates the use of throw:
public class ThrowDemo { public static void main(String[] args) { //Create an array int[] arr = {2,4,52,2}; //Find the corresponding element according to the index int index = 4; int element = getElement(arr, index); System.out.println(element); System.out.println("over"); } /* * Find the corresponding element in the array according to the index */ public static int getElement(int[] arr,int index){ if(arr == null){ /* If the judgment conditions are met, the method will be killed and stopped after throw ing the exception object after execution. End the execution of the current method and notify the caller of the exception. At this time, we need to solve it through exceptions. */ throw new NullPointerException("To access arr Array does not exist"); } //Judge whether the index is out of bounds if(index<0 || index>arr.length-1){ throw new ArrayIndexOutOfBoundsException("Subscript out of bounds, tiezi~~~"); } int element = arr[index]; return element; } }
Note: if a problem occurs, we will throw the problem description class, that is, the exception, that is, return the problem to the caller of the method.
What should be done for the caller. One is to capture, and the other is to continue to state the problem and use throws to declare.
catch exception try... catch
If an exception occurs, the program will be terminated immediately, so we have to deal with the exception:
- The method does not handle, but declares throws, which are handled by the caller of the method.
- Use the statement block of try catch in the method to handle exceptions.
The way to try catch is to catch exceptions.
- Catch exceptions: Java captures targeted statements of exceptions, and you can handle exceptions in a specified way.
The syntax for catching exceptions is as follows:
try{ Monitor codes that may be abnormal }catch(Exception type 1 e){ Code to handle exceptions }catch(Exception type 2 e){ Code to handle exceptions } ....
**try:* * write code that may generate exceptions in this code block for monitoring.
**Catch:** is used to catch certain exceptions and handle the caught exceptions.
- There can be multiple catch blocks that match in order.
- If multiple exception types have a containment relationship, then small up and large down
The demonstration is as follows:
public class TestException { public static void main(String[] args) { try { readFile("Don't knock code Institute Java Secret script.txt"); } catch (FileNotFoundException e) { // e.printStackTrace(); // System.out.println("knock the code carefully, don't always want to get any secrets"); System.out.println(e.getMessage()); } catch (IllegalAccessException e) { e.printStackTrace(); } System.out.println("Keep learning..."); } // If there is a problem when defining a function, it needs to be reported to the caller. It can be declared by using the throws keyword on the method public static void readFile(String filePath) throws FileNotFoundException, IllegalAccessException{ File file = new File(filePath); if(!file.exists()){ throw new FileNotFoundException(filePath+"file does not exist"); } if(!file.isFile()){ throw new IllegalAccessException(filePath + "It is not a file and cannot be read directly"); } //... } }
How to get exception information:
Some viewing methods are defined in the Throwable class:
-
public String getMessage(): get the description information and reason of the exception (when prompted to the user, the error reason will be prompted.
-
public void printStackTrace(): print abnormal trace stack information and output it to the console.
*Contains the type of exception,Cause of abnormality,It also includes the location of the exception,During the development and commissioning phase,Have to use printStackTrace. *
finally block
Finally: there are some specific codes that need to be executed no matter whether the exception occurs or not. In addition, because the exception will cause program jump, some statements cannot be executed. Finally solves this problem. The code stored in the finally code block is bound to be executed.
When must the code be finally executed?
When we open some physical resources (disk file / network connection / database connection, etc.) in the try statement block, we have to finally close the open resources after using them.
finally syntax:
try{ }catch(...){ }finally{ whether try Whether an exception occurs in the catch Whether exceptions are caught or not, it doesn't matter try and catch Is there any in return Statements will be executed } or try{ }finally{ whether try Whether an exception occurs in the try Is there any in return Statements will be executed }
Note: finally cannot be used alone. Whether there is a return statement in try or not, it will be executed!!
finally, the code example is as follows:
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class TestException { public static void main(String[] args) { readFile("Don't knock code Institute Java Secret script.txt"); System.out.println("Keep learning..."); } // If there is a problem when defining a function, it needs to be reported to the caller. It can be declared by using the throws keyword on the method public static void readFile(String filePath) { File file = new File(filePath); FileInputStream fis = null; try { if(!file.exists()){ throw new FileNotFoundException(filePath+"file does not exist"); } if(!file.isFile()){ throw new IllegalAccessException(filePath + "It is not a file and cannot be read directly"); } fis = new FileInputStream(file); //... } catch (Exception e) { //What is caught is the compile time exception, and what is thrown is the run time throw new RuntimeException(e); }finally{ System.out.println("Anyway, the code here must be executed"); try { if(fis!=null){ fis.close(); } } catch (IOException e) { //What is caught is the compile time exception, and what is thrown is the run time throw new RuntimeException(e); } } } }
When the relevant method of exiting the JVM is called only in try or catch, such as System.exit(0), finally will not execute at this time, otherwise finally will always execute.
finally and return
Form 1: come back from try
public class TestReturn { public static void main(String[] args) { int result = test("12"); System.out.println(result); } public static int test(String str){ try{ Integer.parseInt(str); return 1; }catch(NumberFormatException e){ return -1; }finally{ System.out.println("test end"); } } }
Form 2: come back from catch
public class TestReturn { public static void main(String[] args) { int result = test("a"); System.out.println(result); } public static int test(String str){ try{ Integer.parseInt(str); return 1; }catch(NumberFormatException e){ return -1; }finally{ System.out.println("test end"); } } }
Form 3: come back finally
public class TestReturn { public static void main(String[] args) { int result = test("a"); System.out.println(result); } public static int test(String str){ try{ Integer.parseInt(str); return 1; }catch(NumberFormatException e){ return -1; }finally{ System.out.println("test end"); return 0; } } }
Abnormal precautions
-
How to deal with multiple exceptions using capture
- Multiple exceptions are handled separately.
- Multiple exceptions are captured once and processed many times. (recommended)
- Multiple exceptions are captured and processed at a time.
Generally, we use the method of one capture and multiple processing. The format is as follows:
try{ Monitor codes that may be abnormal }catch(Exception type A e){ When try Appears in A Type exception,Just use it catch To capture. Code to handle exceptions }catch(Exception type B e){ When try Appears in B Type exception,Just use it catch To capture. Code to handle exceptions }
Note: this exception handling method requires that the exceptions in multiple catches cannot be the same, and if there is a child parent exception relationship between multiple exceptions in a catch, the child exception needs to be handled in the above catch, and the parent exception needs to be handled in the following catch.
-
Run time exceptions can be thrown without processing. Neither capture nor declare throw.
-
If finally has a return statement, always return the result in finally to avoid this situation
-
If the parent class throws multiple exceptions, when the subclass overrides the parent method, it throws the same exception as the parent class, or it is a subclass of the parent class exception, or it does not throw an exception.
-
The parent method does not throw an exception, and the subclass cannot throw an exception when overriding the parent method. At this time, a compile time exception is generated in the subclass method, which can only be caught and processed, and cannot be declared and thrown
Custom exception
Why do I need to customize exception classes
We talked about different exception classes in Java, which respectively represent a specific exception. In the development, there are always some exceptions that Java developers have not defined. At this time, we define exception classes according to the exceptions of our own business. For example, negative age, negative exam scores, and so on. Can you define exceptions yourself? sure
How to define exception classes:
- Customize a compile time exception: customize the class and inherit from java.lang.Exception.
- Customize a runtime exception class: customize the class and inherit from java.lang.RuntimeException.
Demo custom exception:
Requirements: we simulate the registration operation. If the user name already exists, an exception will be thrown and a prompt: tiezi, the user name has been registered.
First, define a login exception class RegisterException:
// Business logic exception public class RegisterException extends Exception { /** * Empty parameter structure */ public RegisterException() { } /** * * @param message Indicates an exception prompt */ public RegisterException(String message) { super(message); } }
Simulate the login operation, use the array to simulate the data stored in the database, and provide the method to judge whether the current registered account exists.
public class Demo { // The account number already exists in the simulation database private static String[] names = {"bill","hill","jill"}; public static void main(String[] args) { //Call method try{ // Codes with possible exceptions checkUsername("nill"); System.out.println("login was successful");//If there is no exception, the registration is successful }catch(RegisterException e){ //Handling exceptions e.printStackTrace(); } } //Judge whether the current registered account exists //This exception is declared because it is a compile time exception and the caller wants to handle it public static boolean checkUsername(String uname) throws RegisterException{ for (int i=0; i<names.length; i++) { if(names[i].equals(uname)){//If the name is in it, a login exception will be thrown throw new RegisterException("Iron son"+name+"Has been registered!"); } } return true; } }
Conclusion:
- You can derive a subclass from the Exception class or its subclass
- Customarily, a custom exception class should contain two constructors: one is a parameterless constructor, and the other is a constructor with detailed information
- Custom exceptions can only be thrown through throw.
- The most important thing about custom exceptions is the name of the exception class. When an exception occurs, you can judge the exception type according to the name.