Exception Error and exception
What is an exception
- In real life; The situation may not be perfect. For example, you write a module. User input does not necessarily meet your requirements. Your program wants to open a file. The file may not exist or the file format is wrong. You want to read the data of the database, the database may be empty, etc. Our program is running, the memory or hard disk may be full, and so on.
- Software programs are very likely to encounter these abnormal problems during operation. We call them exceptions. The citation is: Exception, which means Exception. These exceptions, or exceptions. How to make the program we write deal with reasonably without crashing.
- Exceptions refer to unexpected conditions during program operation: file missing, network connection failure, illegal parameters, etc.
- The exception occurs during the running of the program, which affects the normal process of program execution.
package huang.Exception; public class Demo01 { public static void main(String[] args) { new Demo01().a(); } public void a(){ b(); } public void b(){ a(); } } //This creates an infinite loop
Simple classification
-
Understand that java exceptions work like songs. You need to master the following three types of exceptions:
-
Checking exception: the most representative checking exception is the exception caused by user error, which is unforeseen by programmers. For example, when a nonexistent file is opened, an exception occurs. These exceptions cannot be simply ignored at compile time.
-
Runtime exceptions: runtime exceptions are exceptions that may be avoided by programmers. Contrary to checking exceptions, runtime exceptions can be ignored at compile time.
-
ERROR: an ERROR is not an exception, but a problem out of the programmer's control. Errors are usually ignored in code, for example; When the stack overflows; A mistake happens. They can't be checked at compile time.
Error
- The Error class object is generated and thrown by the java virtual machine. Most errors have nothing to do with the operation performed by the coder
- Java virtual machine error. When the JVM no longer has the memory resources required to continue the operation; OutofMemoryError appears. When these exceptions occur, the Java virtual machine (JVM) generally selects thread termination.
- In addition, when the virtual machine attempts to execute the application, such as class definition error (NoClassDefFoundError) and link error (LinkageError). These errors are not traceable because they are outside the control and processing power of the application, and most of them are not allowed when the program is running.
Exception
-
There is an important subclass runtimeException (runtime Exception) in the Exception branch
-
ArrayIndexOutOfBoundsException (array subscript out of bounds)
-
NullPointerException (null pointer exception)
-
ArithmeticException (arithmetic exception)
-
MissingResourceException (missing resource)
-
Exceptions such as ClassNotFoundException (class not found). These exceptions are not checked. The program can choose to capture and handle them or not.
-
These exceptions are generally caused by program logic errors. The program should avoid such exceptions as far as possible from the logical point of view;
-
The difference between Error and Exception: Errpr is usually a catastrophic Error that cannot be controlled and handled by the program. When these exceptions occur, the Java virtual machine (JVM) will generally choose to terminate the thread; Exceptions can usually be handled by the program, and these exceptions should be handled as much as possible in the program.
Catch and throw exceptions
-
Throw exception
-
Catch exception
-
Five keywords for exception handling: 1, try, 2, catch, 3, finally, 4, throw, 5, throws
-
You can use shortcut keys to generate: select the exception statement to be captured with the mouse, for example: (System.out.println(a/b) 😉 try catch finally
package huang.Exception; public class TestDemo01 { public static void main(String[] args) { int a =1; int b =0; //We know that the divisor cannot be 0, so we will report an exception (arithmetexception:) //But we can catch exceptions with try catch finally try { //try monitoring area System.out.println(a/b); }catch (ArithmeticException e){ //Catch (the type of exception you want to catch) the highest level of catching exceptions is Throwable, so exceptions can be caught System.out.println("Program exception, variable b Cannot be 0"); }finally { //finally, deal with the aftermath System.out.println("finally"); //Try catch these two areas must be finally. The area can not be written } //Suppose you want to capture multiple exceptions from small to large } } //--------------------------------------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------------------------------------- package huang.Exception; public class TestDemo02 { public static void main(String[] args) { int a = 1 ; int b = 0 ; try { System.out.println(a/b); }catch (Error error){ System.out.println("Error"); }catch (Exception e){ System.out.println("Exception"); }catch (Throwable throwable){ System.out.println("Throwable"); }finally { System.out.println("finally"); } //You can write multiple catch es, but write the largest one at the bottom //You can use shortcut keys to generate: select the exception statement to be captured with the mouse, for example: (system. Out. Println (A / b);) try catch finally } } //--------------------------------------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------------------------------------- package huang.Exception; public class TestDemo03 { public static void main(String[] args) { int a = 1; int b = 0 ; try { if (b==0){ // throw thorws throw new ArithmeticException(); //Actively throw exception } System.out.println(a/b); } catch (Exception e) { e.printStackTrace(); //This sentence means printing the wrong stack information } finally { } } } //throw usually throws an exception in a method //--------------------------------------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------------------------------------- ackage huang.Exception; public class TestDemo04 { public static void main(String[] args) { try { new TestDemo04().test(1,0); } catch (ArithmeticException e) { e.printStackTrace(); } } //Assuming that this exception cannot be handled in this method, an exception is thrown on the method public void test(int a, int b) throws ArithmeticException { if (b == 0) { // throw thorws throw new ArithmeticException(); //Actively throw an exception. Generally used in methods } //A simple summary: try catch can run even if it encounters an error. Throw throws is to throw an exception to us when running } }
Custom exception
-
Using the built-in Exception class in java can describe most exceptions during programming. In addition, users can also customize exceptions and user-defined Exception classes. They only need to inherit the Exception class.
-
Use custom exception classes in the program. The answer can be divided into the following steps:
1. Create custom exception class
2. Throw an exception object through the throw keyword in the method.
3. If the exception is handled in the method currently throwing the exception, you can use the try catch statement to catch the exception and handle it; otherwise, indicate the exception to be thrown to the method caller through the throws keyword in the method declaration; continue to the next step.
4. Catch and handle exceptions in the caller of the exception method
package huang.exception.demo02; //Custom exception //Once you inherit the Exception class, this class is a custom Exception class public class MyException extends Exception{ //An exception is thrown when the number > 10 is passed private int detail; public MyException(int a){ this.detail = a; } //toString: abnormal print information @Override public String toString() { return "MyException{" + "detail=" + detail + '}'; } } //----------------------------------------------------------------------- //----------------------------------------------------------------------- package huang.exception.demo02; public class TestDemo01 { //There may be abnormal methods static void test(int a ) throws MyException { System.out.println("The parameters passed are"+a); if (a > 10){ throw new MyException(a); //Throw Alt + Enter here } System.out.println("OK"); } public static void main(String[] args) { try { test(1); } catch (MyException e) { e.printStackTrace(); System.out.println("MyException=>"+e); } } }
Experience summary in practical application
- When dealing with run-time exceptions, logic is used to reasonably avoid and assist in try catch processing
- After multiple catch blocks, you can add a catch (Exception) to handle exceptions that may be missed
- For uncertain code, try catch can also be added to handle potential exceptions
- Try to handle exceptions. Remember to simply call printStackTrace() to print out
- How to handle exceptions should be determined according to different business requirements and exception types
- Try to add finally statement blocks to free up the occupied memory