JAVA study notes 07-abnormal

abnormal

1. The concept and system of
exceptions. Exceptions: abnormal situations that occur during the execution of the program, which eventually lead to abnormal stop of the JVM.
Throwable system:
Error: serious error, error that cannot be processed
Exception: exception, program after the exception The operator can correct by way of code to make the program continue to run

2. Exception handling

Throw an exception Throw
function:
throw a specified exception in the specified method
Syntax:
throw new xxxException;
Note:
1. The throw keyword must be written inside the method
2. The new object after the throw keyword must be a subclass of Exception or Exception Object
3. Throw keyword throws the specified exception object, we must deal with this exception object

public class Demo01 {
    
    
    public static void main(String[] args) {
    
    
        int[] array=null;
        int e=getElement(array,0);
        System.out.println(e);
    }
    public static int getElement(int[] array,int index){
    
    
        if(array==null){
    
    
            throw new NullPointerException("传递数组为空");
        }
        int res=array[index];
        return res;
    }   //运行期异常,默认交给JVM处理
}

3. Declare exception throws
Declare exception: identify the problem and report it to the caller. If the method throws a compile-time exception through throw, but does not catch the exception, then it must be declared through throws and let the caller handle it.
Syntax:
modifier return value type method name (parameter) throws exception class name 1{}
Note:
1 The .throws keyword must be written at the method declaration
2. The exception declared after the throws keyword must be Exception or a subclass of Exception
3. If multiple exception objects are thrown inside the method, then multiple exceptions must also be declared after throws ; If the thrown multiple exception objects have a child-parent relationship, then you can directly declare the parent exception
. 4. Call a method that declares throwing an exception, we must deal with the declared exception
or continue to use the throws statement to throw, hand in Handling to the caller of the method, and finally to the JVM
or try...catch to handle the exception by itself

public class Demo02 {
    
    
    public static void main(String[] args) throws FileNotFoundException {
    
    
        readFile("c:\\a.txt");
    }
    public static void readFile(String fileName) throws FileNotFoundException{
    
    
        if(!fileName.equals("c:\\a.txt")){
    
    
            throw new FileNotFoundException("传递路径不是c:\\a.txt");
        }
        System.out.println("路径没有问题,读取文件");
    }
}

4. Catch the exception try...catch
If an exception occurs, the program will be terminated immediately, so we have to handle the exception:
1. The method does not handle it, and the caller of the method handles it (throws)
2. Use try...catch in the method Statements to handle exceptions.
Catch exceptions: JAVA captures targeted statements and can handle exceptions in a specified way.
Syntax:
try{code that may be abnormal
}catch(exception type e){}
code for handling exceptions
}
Note:
1. Multiple exception objects may be thrown in the
try , then multiple catches can be used to handle these exception objects . 2. If an exception occurs in the try, then the exception handling logic in the catch will be executed, and the catch will be executed. The processing logic in, continue to execute the code after try...catch; if there is no exception in try, then the processing logic in catch will not be executed, and the code after try...catch will continue to be executed

public class Demo02 {
    
    
    public static void main(String[] args){
    
    
        try{
    
    
            readFile("c:\\d.txt");
        }catch(FileNotFoundException e){
    
    
            System.out.println("传递文件路径错误");
        }
    }
    public static void readFile(String fileName) throws FileNotFoundException {
    
    
        if(!fileName.equals("c:\\a.txt")){
    
    
            throw new FileNotFoundException("传递路径不是c:\\a.txt");
        }
        System.out.println("路径没有问题,读取文件");
    }
}

Some viewing methods are defined in the Throwable class:
public String getMessage(): get the description of the exception
public String toString(): get the type and description of the exception
public void printStackTrace(): print the stack trace of the exception and output it to the control station

public class Demo04 {
    
    
    public static void main(String[] args){
    
    
        try{
    
    
            readFile("c:\\d.txt");
        }catch(FileNotFoundException e){
    
    
            System.out.println(e.getMessage()); //传递路径不是c:\a.txt
            System.out.println(e.toString());   //java.io.FileNotFoundException: 传递路径不是c:\a.txt
            e.printStackTrace();    //全面信息
        }
    }
    public static void readFile(String fileName) throws FileNotFoundException {
    
    
        if(!fileName.equals("c:\\a.txt")){
    
    
            throw new FileNotFoundException("传递路径不是c:\\a.txt");
        }
        System.out.println("路径没有问题,读取文件");
    }
}

5. Finally code block
There are some specific codes that need to be executed regardless of whether an exception occurs or not.
Note:
1.finally cannot be used alone
2.finally is generally used for resource release
Syntax:
try...catch...finally

public class Demo03 {
    
    
    public static void main(String[] args){
    
    
        try{
    
    
            readFile("c:\\d.txt");
        }catch(FileNotFoundException e){
    
    
            System.out.println(e.getMessage()); //传递路径不是c:\a.txt
        }
        finally{
    
    
            System.out.println("资源释放");
        }
    }
    public static void readFile(String fileName) throws FileNotFoundException {
    
    
        if(!fileName.equals("c:\\a.txt")){
    
    
            throw new FileNotFoundException("传递路径不是c:\\a.txt");
        }
        System.out.println("路径没有问题,读取文件");
    }
}

Child parent class exception:
If the parent class throws more than one field, when the child class overrides the parent class method, it will throw the same exception as the parent class or a subclass of the parent class exception or not throw an exception
if the parent class does not When an exception is thrown, the subclass cannot throw an exception when it overrides the method of the parent class. At this time, the subclass can only capture and handle the exception when the method is overridden.
6. Custom exceptions cannot be declared .
Note:
1. Custom exceptions are generally They all end with Exception
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 is thrown inside the method, the exception must be handled, or throws Either try...catch
inherits RuntimeException: then the custom exception class is a runtime exception, which does not need to be handled and is handed over to the virtual machine

public class RegisterException extends Exception{
    
    
    public RegisterException(){
    
    
        super();
    }
    public RegisterException(String message){
    
    
        super(message);
    }
}
public class Demo05 {
    
    
    static String[] usernames={
    
    "Kobe","James","Jordan"};

    public static void main(String[] args) {
    
    
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入用户名:");
        String username=sc.next();
        checkUsername(username);
    }
    public static void checkUsername(String username){
    
    
        for (String s : usernames) {
    
    
            if(s.equals(username)){
    
    
                try {
    
    
                    throw new RegisterException("用户已经被注册!");
                } catch (RegisterException e) {
    
    
                    e.printStackTrace();
                    return;
                }
            }
        }
        System.out.println("注册成功!");
    }
}

Guess you like

Origin blog.csdn.net/qq_44708714/article/details/106908340