Basic applications with exceptions in Java (1), Java applications (
In Java, we treat exceptions as an object. It is the introduction of the exception mechanism that makes our programs more robust. An exception indicates an abnormal condition or an error condition, which is simply an event that interrupts the normal instruction flow. Program Control will unconditionally throw it to a specific code segment, where exceptions will be caught and handled, thus separating the error handling from the normal processing of the program, and the error can be handled independently.
Exceptions are represented by instances of the Exception class and its subclass. Most packages define their own Exception types, which are usually subclasses of exceptions. We can also define the Exception types by ourselves. When an error condition occurs, you should have a piece of code to create an exception object. The Exception object must be passed as a parameter to the code block that is responsible for processing. This involves throwing and capturing exceptions.
In addition to exceptions and error classes. The Error class usually indicates some major errors or virtual machine errors and should not be captured by the program. There are two types of exceptions: runtime exception and compilation exception, or unchecked exception and checked exception. The IO and SQL exceptions we usually encounter are checked exceptions. For such exceptions, the compiler requires us to handle them. The runtime exception can be taken over by a virtual machine without being processed.
When an exception occurs, you can either directly handle it or throw it up, waiting for the upper-layer method to be called for processing. If it is not processed at all, Thread. run () will throw the Thread if it is multithreading, main () will throw the Thread if it is a single Thread, and the corresponding Thread or the whole program will exit. Runtime Exception and Error can be not processed. Therefore, when a program encounters such errors, it terminates and exits if it does not process the block program.
Exception Handling Method:
1. try-catch-finally structure Exception Handling
Try {// normal code, including code that may cause errors // if return exists, return finally first (Exception type Exception e) {// Exception Handling} finally {// finally block. The exit will run no matter whether the program is abnormal or not}
2. Do not process it for now. Throw it up
Throw is used to manually throw an exception (an exception that cannot be recognized by the system). throws declares the error type that may be generated by the method. When this method is called, try-catch is used. If it is not declared, try-catch must be performed in the method.
Public void setAge (int age) throws Exception {if (age> = 15 & age <= 40) {this. age = age;} else {throw new Exception ("age must be between 15 and 40! ");}
In this example, when the setAge method is called, try-catch is processed, or continue to throw up.