1. What is an exception
In actual work, the situation encountered can not be very perfect. For example, for a module you write, the 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 in the database, the data may be empty, etc. If our program runs again, the memory or hard disk may be full. wait.
During the operation of the software program, it is very likely to encounter these abnormal problems just mentioned. We call them exceptions, which means exceptions. These, exceptions, or exceptions, how can we make our program deal with them reasonably. Without the program crashing.
Exceptions refer to unexpected conditions during program operation, such as file missing, network connection failure, illegal parameters, etc.
The exception occurs during the program running, which affects the normal program execution process.
package com.hjb.exception; public class Demo01 { /* public static void main(String[] args) { new Demo01().a(); } public void a(){ b(); } public void b(){ a(); } */ public static void main(String[] args) { System.out.println(11/0); } }
2. Simple classification
To understand how Java exception handling works, you need to master the following three types of exceptions:
Checking exception: the most representative checking exception is the exception caused by user errors or problems, which cannot be foreseen by programmers. For example, when you want to open a nonexistent file, an exception occurs. These exceptions cannot be simply ignored at compile time.
Runtime exceptions: runtime exceptions are exceptions that may be avoided by programmers. In contrast 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, an error occurs, and they cannot be checked during compilation.
3. Exception architecture
- Java treats exceptions as objects and defines a base class java Lang. throwable is the superclass of all exceptions.
- Many Exception classes have been defined in Java APl. These Exception classes are divided into two categories: Error and Exception.
3.1 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 running error. OutOfMemoryError will appear when the JVM no longer has the memory resources required to continue the operation. When these exceptions occur, the Java virtual machine (JVM) will generally choose 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.
3.2 Exception
There is an important subclass RuntimeException (runtime Exception) in the Exception branch
- Arraylndexofboundsexception (array subscript out of bounds)
- NullPointerException (null pointer exception)
- Arithmeticexception (arithmetic exception)
- Missing resourceexception
- Classnotfoundexception (class not found) and other exceptions. 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: Error is usually a catastrophic and fatal 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.
4. Exception handling mechanism
Throw exception
Catch exception
Five keywords for exception handling:
try,catch,finally,throw,throws
package com.hjb.exception; public class Test { public static void main(String[] args) { int a = 1; int b = 0; //Suppose you want to catch multiple exceptions, from small to large try{//try monitoring area System.out.println(a/b); }catch(Error e){//Catch exception System.out.println("Error"); }catch (Exception e){ System.out.println("Exception"); }catch (Throwable t){ System.out.println("Throwable"); }finally{//Deal with the aftermath System.out.println("finally"); } //finally, it can not be used, such as IO, resource, and shutdown } public void a(){ b(); } public void b(){ a(); } }
package com.hjb.exception; public class Test2 { public static void main(String[] args) { int a = 1; int b = 0; //Ctrl + Alt + T try { System.out.println(a/b); } catch (Exception e) { e.printStackTrace();//Print wrong stack information } finally { } } }
package com.hjb.exception; public class Test { public static void main(String[] args) { try { new Test().test(1,0); } catch (ArithmeticException e) { e.printStackTrace(); } finally { } } //Assuming that this exception cannot be handled in this method, the method throws an exception public void test(int a,int b) throws ArithmeticException{ if (b==0){//Actively throw exceptions throw new ArithmeticException();//Actively throw exceptions, which are generally used in methods } System.out.println(a/b); } } /* //Suppose you want to catch multiple exceptions, from small to large try{//try Monitoring area if (b==0){//Actively throw exceptions throw new ArithmeticException();//Actively throw exception } System.out.println(a/b); }catch(Error e){//Catch exception System.out.println("Error"); }catch (Exception e){ System.out.println("Exception"); }catch (Throwable t){ System.out.println("Throwable"); }finally{//Deal with the aftermath System.out.println("finally"); } //finally No, such as IO, resource, shutdown */
5. Custom exception
Using Java's built-in Exception class can describe most exceptions during programming. In addition, users can customize exceptions. You can customize the Exception class by inheriting the Exception class.
Using custom exception classes in programs can be roughly divided into the following steps:
1. Create a custom exception class.
2. Throw an exception object through the throw keyword in the method.
3. If an exception is handled in the method that currently throws an exception, you can use the try catch statement to capture and handle it; Otherwise, use the throws keyword at the method declaration to indicate the exception to be thrown to the method caller, and continue with the next operation.
4. Catch and handle exceptions in the caller of the exception method.
package com.hjb.exception.Demo02; //Custom exception class public class MyException extends Exception{ //Transfer number > 10; private int detail; public MyException(int a) { this.detail = a; } //toString: abnormal print information @Override public String toString() { return "MyException{" + "detail=" + detail + "}"; } }
package com.hjb.exception.Demo02; public class Test { //Possible exception methods static void test(int a) throws MyException { System.out.println("The parameters passed are:"+a); if (a>10){ throw new MyException(a);//Throw } System.out.println("OK"); } public static void main(String[] args) { try { test(11); } catch (MyException e) { System.out.println("MyException=>"+e); } } }
6. Experience summary in practical application
- When handling runtime 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, you can also add try catch to handle potential exceptions
- Try to handle exceptions, and never 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 release the occupied resources