We need to know that using Java's built-in exception class can describe most exceptions during programming. In addition, we can also extend the Exception class to define our own exception class during programming, and then specify which methods are generated according to the needs of the program. Such anomalies.
Format of custom exception class:
publicclass exception class name extendsException {no-parameter construction with parameters construction}
For example:
publicclassDotcppExceptionextendsException{//Construction without parameters publicDotcppException(){}//Construction with parameters publicDotcppException(Stringmessage){//Exception error message super(message);}}
When declaring a method, you can use the throws keyword to declare several exceptions to be generated, and specify the operation to generate the exception in the method body, that is, create an object with the corresponding exception class and throw it using the throw keyword. This exception object causes the method to end execution. The program must call methods that may cause exceptions in the try-catch block statement, where the function of catch is to capture the exception object thrown by the throw keyword.
Note : throw is a keyword in Java. The function of this keyword is to throw an exception. Throw and throws are two different keywords.
Summarize:
(1) When handling runtime exceptions, use logic to avoid them and assist try-catch in handling them;
(2) After the multiple catch blocks, you can add a catch (Exception) to handle exceptions that may be missed;
(3) For uncertain code, try-catch can also be used to handle potential exceptions;
(4) Try to handle exceptions as much as possible, remember to simply call printStackTrace() to print;
(5) How to handle exceptions specifically depends on different business needs and exception types;
(6) Try to add finally statements to release occupied resources.