What is an exception
In practice, the situation encountered can not be perfect
During the running of the software program, we may encounter these abnormal problems just mentioned
Exceptions refer to various unexpected situations during the operation of the program, such as not finding the file, network connection failure, illegal parameters, etc
The exception occurs during the program running, which affects the normal program execution process
Anomalies fall into three categories:
- Checking exception: represents an exception caused by a user error or problem, which cannot be foreseen by the programmer
- Runtime exceptions: exceptions that programmers may avoid
- Error: the error is not an exception, but a problem out of the programmer's control. The error is ignored in the code
Exception architecture
Java treats exceptions as objects and defines a base class java.lang.Throwable as the superclass of all exceptions
Many exception classes have been defined in the Java api, which can be roughly divided into error and exception exceptions
error
The error object is generated and thrown by the java virtual machine. Most of the errors have nothing to do with the operations performed by the coder
java virtual machine running error. When the jvm no longer has the memory resources required to continue to perform all operations, an outofMemoryError will appear. When these exceptions occur, java virtual machines generally choose thread termination
In addition, when the virtual machine attempts to execute applications, such as NaClassDefFoundError and 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
- Array index out of bounds IndexOutOfBoundsException
- Null pointer exception NullPointerException
- Arithmetic exception ArithmaticException
- Missing resource MissingResourceException
- No exceptions such as ClassNotFoundException can be found. These exceptions are not checked. The program can choose to capture and handle them or not
These exceptions are generally caused by errors in program logic. The program should avoid such exceptions as far as possible from the perspective of logic
The difference between Error and Exceptipn
Error: a catastrophic fatal error that cannot be controlled and handled by the program. When an exception occurs, the jvm chooses to terminate the process
exception: usually, it can be handled by the program, and these exceptions should be taken out as far as possible in the program
java exception handling mechanism
- Throw exception
- Catch exception
- Five keywords for exception handling: try catch finally throw throws
e.printStactTrace() / / print wrong stack information
exception handling
package exception; public class Demo02 { public static void main(String[] args) { int a=1; int b=0; // try {/ / monitoring area // if (b==0){ // throw new ArithmeticException();// Actively throw exception // } // System.out.println(a/b); // }catch (Error e){//catch catch exception // System.out.println("program exception, variable b cannot be 0"); // }finally {/ / deal with the aftermath // System.out.println("finally"); // } // //finally, you can not. Suppose io is closed and put in it // System.out.println("============================="); // try { // new Demo02().A(); // }catch (Exception e){ // System.out.println("Exception"); // }catch (Error e){ // System.out.println("error"); // }catch (Throwable t){//catch (want to get exception type) // System.out.println("throwable"); // }finally { // System.out.println("finally"); // } System.out.println("========================="); new Demo02().test(1,0); } public void A(){ B(); } public void B(){ A(); } public void test(int a,int b) throws ArithmeticException{//Exception thrown on method System.out.println(a/b); } }
Custom exception
java built-in Exception class can solve most exceptions in java. In addition, you can customize exceptions by inheriting Exception class
General steps:
- Create custom exception class
- Throw an exception object through the throw keyword in the method
- If the exception is handled in the current method that throws the exception, use try catch to catch and handle the exception. Otherwise, throw an exception in the throes keyword at the method declaration and continue to the next step
- Catch and handle exceptions in the caller of the exception method
package exception.Demo03; //Custom exception class public class MyException extends Exception{ //Pass numbers > 10: private int detail; public MyException(int a){ this.detail=a; } //toString: abnormal print information @Override public String toString() { return "MyException{" + detail + '}'; } }
package exception.Demo03; public class Test { //There may be abnormal methods static void test(int a) throws MyException { if (a>10){ throw new MyException(a); } System.out.println("OK"); System.out.println("The parameters passed are:"+a); } public static void main(String[] args) { try { test(11); } catch (MyException e) { // e.printStackTrace(); System.out.println("MyException=>"+e); } } }
summary
- Handling exceptions adopts logic to avoid and assist try catch at the same time
- Multiple catch, add a maximum exception as much as possible, such as Exception Catch (exception)
- Uncertain code, plus try catch exception handling
- Handle exceptions as much as possible and remember to print only exceptions
- How to handle exceptions should be determined according to different business requirements and types
- Try to use the finally statement block of Tianjian to release the occupied resources