1. What is abnormal?
Exceptions are some errors in the program, but not all errors are abnormal, and errors can sometimes be avoided.
For example, if your code is missing a semicolon, then the result will be an error java.lang.Error;
If you use System.out.println (11/0), then you are throwing a java.lang.ArithmeticException because you are dividing by 0.
- The user entered illegal data.
- The file to be opened does not exist.
- The connection was interrupted during network communication, or the JVM memory overflowed.
- Checkable anomalies: The most representative checkable anomalies are those caused by user errors or problems, which are unforeseeable by programmers. For example, when you want to open a file that does not exist, an exception occurs. These exceptions cannot be simply ignored during compilation.
- Run-time exceptions: Run-time exceptions are exceptions that may be avoided by programmers. In contrast to checked exceptions, runtime exceptions can be ignored at compile time.
- Error: Error is not an exception, but a problem that is out of programmer control. Errors are usually ignored in the code. For example, when the stack overflows, an error occurs and they are not detected during compilation.
2. Common Exception class hierarchy
Input and output exception: IOException
Arithmetic exception class: ArithmeticExecption
Null pointer exception class: NullPointerException
Type cast exception: ClassCastException
Operation database exception: SQLException
File not found exception: FileNotFoundException
Array negative subscript exception: NegativeArrayException
Array index out of bounds exception: ArrayIndexOutOfBoundsException
Abnormal violation of security principles: SecturityException
File ended abnormally: EOFException
String to number exception: NumberFormatException
Method not found exception: NoSuchMethodException
3. Exception handling
3.1 Catching exceptions through try and catch
try
{
Possible exception
} catch (Exception type exception name (variable)) {
Code for exception handling
} catch (Exception type exception name (variable)) {
Code for exception handling
} ...
[finally {
Release resource code;
}]
package exception; import java.io.IOException; /*** * @ClassName: TestException * @Description: TODO * @Auther: chujiu * @Date: 2020/4/13 7:15 * @version : V1.0 */ public class TestException { public int method(){ try { int i = 5 / 0; //算术异常 System.out.println("无异常"); return 1; } catch (Exception e) { e.printStackTrace(); System.out.println("有异常"); return 2; } finally { System.out.println("执行fianlly"); return 3; } } public static void main(String[] args){ TestException te = new TestException(); System.out.println(te.method()); } }
- catch cannot exist independently of try.
- Adding finally block after try / catch is not mandatory.
- After the try code, there can be neither catch block nor finally block.
- No code can be added between try, catch, and finally blocks.
- First of all, it is not easy to understand the fact: even if there are return, break, continue and other statements in the try block that change the execution flow, finally will be executed.
- The return in finally will overwrite the return value in try or catch.
- The return or exception in finally will suppress (eliminate) the exception in the previous try or catch block.
3.2 throw keyword throws an exception
Refers to artificially throwing an exception object in the method (this exception object may be instantiated by itself or throwing an existing); used to throw an exception.
3.3 Throwing exceptions via throws
Used in method signatures to declare exceptions that the method may throw. The main method can also use throws to throw. If throws are used in the main method, it means that there is no mandatory exception handling in the main method. If an exception occurs, it is handed over to the JVM for default processing, which will cause the program to interrupt execution.
package exception; import java.io.IOException; /*** * @ClassName: TestException1 * @Description: TODO * @Auther: chujiu * @Date: 2020/4/13 7:17 * @version : V1.0 */ public class TestException1 { public static void method2() throws IOException { int i = 0; if (i == 0) { throw new IOException("除以0错误"); } int x = 5 / i; System.out.println("No exception" ); } public static void method1 () { try { method2 (); } catch (IOException e) { e.printStackTrace (); System.out.println ( "There is an exception" ); } finally { System. out.println ( "Execute fianlly" ); } } public static void main (String [] args) { method1 (); } }
4. Custom exception
The custom exception should always contain the following constructor:
a parameterless constructor and
a constructor with String parameters, and passed to the parent class constructor.
A String parameter and a Throwable parameter are passed to the parent class constructor. A constructor
with a Throwable parameter is passed to the parent class constructor.
The complete source code of the IOException class:
package java.io; public class IOException extends Exception { static final long serialVersionUID = 7818375828146090155L; public IOException() { super(); } public IOException(String message) { super(message); } public IOException(String message, Throwable cause) { super(message, cause); } public IOException(Throwable cause) { super(cause); } }
package exception; import java.util.Scanner; / ** * * @ClassName: DemoRegisterException * @Description: TODO * @Auther: chujiu * @Date: 2020/4/13 7:17 * @version : V1.0 * / public class DemoRegisterException { // 1. Use the array to save the registered user names (database) static String [] usernames = {"张三", "李四", "王 五" }; public static void main (String [ ] args) / * throws RegisterException * / { // 2. Use Scanner to get the registered user name (front end, page) entered by the user Scanner sc =new Scanner (System.in); System.out.println ( "Please enter the user name you want to register:" ); String username = sc.next (); checkUsername (username); } // 3. Define a method, Judging the registered user name entered by the user public static void checkUsername (String username) / * throws RegisterException * / { // Traverse the array that stores the registered user names, and obtain each user name for (String name: usernames) { // Use the obtained user name to compare with the user name entered by the user if (name.equals (username)) { // true: the user name already exists, throw a RegisterException exception to inform the user "pro, the user name has been registered "; try{ throw new RegisterException ("Pro, this username has already been registered" ); } catch (RegisterException e) { e.printStackTrace (); return ; // End method } } } // If the loop is over, no duplicates have been found user name, user prompts, "Congratulations, the registration is successful!"; System.out.println ( "Congratulations, successfully registered!" ); } } // exception class class RegisterException the extends / * Exception * / RuntimeException { // add An empty parameter constructor publicRegisterException () { super (); } / * Add a constructor with exception information.Check the source code and find that all exception classes will have a constructor with exception information.The parent method will call the constructor with exception information. Let the parent class handle this exception message * / public RegisterException (String message) { super (message); } }
Reference article: https://www.cnblogs.com/niujifei/p/11452826.html