Custom exception:
The exception classes provided by java are not enough for us to use, we need to define some exception classes ourselves
Format:
public class XXException extends Exception|RuntimeException{
Add a constructor with empty parameters
Add a constructor with exception information
}
Notice:
1. The custom exception class generally ends with Exception, indicating that the class is an exception class
2. Custom exception class must inherit Exception or RuntimeException
Inherit Exception: Then the custom exception class is a compile-time exception. If a compile-time exception occurs, it must be handled, either throws or try catch
Inherit RuntimeException: Then the custom exception is a runtime exception, which does not need to be handled, and is handed over to the virtual machine for processing and interrupt processing.
Exercise: We simulate user operations, if the user already exists, it will prompt an error, if it does not exist, it will prompt success
analyze:
1. Use an array to save the registered user name (database)
2. Use Scanner to obtain the registered user name entered by the user (front end, page)
3. Define a method to judge the user name entered by the user
Traverse the array of registered usernames to get each username
Use the obtained username to compare with the username entered by the user
true:
The username already exists, and a RegisterException is thrown, telling the user "Dear, this username has already been registered"
false:
continue iterating through the array
If the loop ends and no duplicate user name is found, prompt the user "Congratulations, the registration is successful!"
Custom MyException class
Extend the Exception interface, you can customize the output statement
package test;
import java.util.Scanner;
public class MyException extends Exception{
//添加一个空参数的构造方法
public MyException() {
super();
}
//添加一个带异常信息的构造方法
//查看源码发现,所有异常类都会有一个带异常信息的构造方法,方法内部调用父类异常信息的构造方法,
//让父类处理
public MyException(String message){
super(message);
}
}
package test;
import java.util.Scanner;
public class DemoMyException {
static String[] s = {"张三","李四","王五"};
public static void main(String[] args) throws Exception{
System.out.println("请输入用户名:");
Scanner sc = new Scanner(System.in);
String user = sc.next();
checkName(user);
}
public static void checkName(String username) throws MyException{
for(String name: s){
if(username.equals(name)){
throw new MyException("亲,该用户名已经被注册了!");
}
}
System.out.println("恭喜您,注册成功!");
}
}
Here is Exception compilation exception, so it must be processed, so throw will be thrown to the original MyException class in checkName for processing
2. If it is Extends runtimeException, it can be directly processed by JVM without throw, as shown in the figure below