java: the basis of exception handling (the use of several keywords)

When writing code, we need to pay attention to that sometimes the operation may bring some errors. In order to keep the program running, we need to use the exception handling mechanism of java.

Try catch function

Try catch function is the most common and important function in exception handling. Its functions are as follows:
Execute the code in try first, and then catch will receive the exception if an error is encountered. It may not be clear. Let's use a piece of code to explain:

package workwitherror;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class Error {
    public static void main(String[] args) {
        File music = new File("D://Qqmusic. Exe "); / / this is the object for which a file has been created, and the path is the qqmusic.exe file on disk D

        try {
            System.out.println("Trying to open D Under disk directory qqmusic.exe Document:");
            new FileInputStream(music);
            System.out.println("Open successfully!");
        }catch(FileNotFoundException e){
            System.out.println("The file was not found!");
            e.printStackTrace();
        }finally{
            System.out.println("Your operation has been completed. You are about to exit the program···");
        }

    }
}

As shown in the above code, we first declare a file object music, and then try to catch it. We try to open such a file in the path. On my computer, there is no such program in this directory, so if you press the java compiler, it will report an error FileNotFoundException. Therefore, the FileNotFoundException that we reported an error in try will be caught by catch, and then the code in catch will be executed.

It should be noted that:
1. e.printtStackTrace() in the catch code can help you to check the error location and cause, but it will not stop running as if there is no exception handling;
2.finally means that the code will run anyway. If there is an exception, it will run; if there is no exception, it will also run.
3. For finally, if there is a return value in try, a return value in catch, and a return value in finally, it must return the return value in finally, because finally will run anyway.

Catch all kinds of exceptions

Just now we found that we specifically wrote out which Exception to catch, that is, the above Exception to catch FileNotFoundException. But again, we can catch all kinds of exceptions without specifying which Exception to catch, that is, we can use the parent Exception of the Exception. Here is the code:

package workwitherror;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class Error {
    public static void main(String[] args) {
        File music = new File("D://Qqmusic. Exe "); / / this is the object for which a file has been created, and the path is the qqmusic.exe file on disk D

        try {
            System.out.println("Trying to open D Under disk directory qqmusic.exe Document:");
            new FileInputStream(music);
            System.out.println("Open successfully!");
        }catch(Exception e){//Compared with the above, the only change
            System.out.println("The file was not found!");
            e.printStackTrace();
        }finally{
            System.out.println("Your operation has been completed. You are about to exit the program···");
        }

    }
}

As shown in the code above, we annotated where the only changes were made. In this way, any error reported will be caught.
However, in this way, we can't write out what to do next for each situation. Therefore, we need to use multiple exception capture methods:

Multiple exception catching method

There are two ways to capture multiple exceptions:
1. Write two catch es respectively, which is simple and clear;
2. Use a catch to catch two exceptions at the same time. The advantage is that the code is more compact, but you need to indicate which subclass the exception is.
As follows: there are two exceptions in try.

package workwitherror;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Error {
    public static void main(String[] args) {
        File music = new File("D://Qqmusic. Exe "); / / this is the object for which a file has been created, and the path is the qqmusic.exe file on disk D

        try {
            System.out.println("Trying to open D Under disk directory qqmusic.exe Document:");
            new FileInputStream(music);
            System.out.println("Open successfully!");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
            Date d = sdf.parse("2020-1");
        }catch(FileNotFoundException e){
            System.out.println("The file was not found!");
            e.printStackTrace();
        }catch(ParseException e) {
            System.out.println("Date format parsing error!");
            e.printStackTrace();
        }finally {
            System.out.println("Your operation has been completed. You are about to exit the program···");
        }

    }
}

This is the first way to catch exceptions with two catches.
However, it should be noted that when the first exception is caught in the try, the code in the try will not continue to execute, so the second exception here will not be caught.

The second way is to catch directly:

package workwitherror;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Error {
    public static void main(String[] args) {
        File music = new File("D://Qqmusic. Exe "); / / this is the object for which a file has been created, and the path is the qqmusic.exe file on disk D

        try {
            System.out.println("Trying to open D Under disk directory qqmusic.exe Document:");
            new FileInputStream(music);
            System.out.println("Open successfully!");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
            Date d = sdf.parse("2020-1");
        }catch(FileNotFoundException|ParseException e){//The catch bracket can also be replaced with Exception, that is, the parent class of the Exception, which can directly catch two kinds of exceptions.
            if(e instanceof FileNotFoundException)
                System.out.println("The file was not found!");
            if(e instanceof ParseException)
                System.out.println("Date format parsing error!");
            e.printStackTrace();
        }finally {
            System.out.println("Your operation has been completed. You are about to exit the program···");
        }

    }
}

This is the second way to catch exceptions, which is to catch them directly with a catch.

throws

The keywords throws are used to throw an exception.
What is an exception thrown? That is to say, if there is an error in the operation of a method, leave the exception to try catch, and the method itself does not handle it.

Use a piece of code to explain the following:

package workwitherror;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class Error {
    public static void main(String[] args) {
        method1();
    }

    public static void method1(){
        try{
            method2();
        }catch(Exception e){
            e.printStackTrace();
            System.out.println("Operation failed!");
        }
    }
    public static void method2() throws FileNotFoundException {
        File f = new File("D://qqmusic.exe");
        System.out.println("Try to open the file:");
        new FileInputStream(f);
        System.out.println("Open file succeeded!");
    }

}

As shown in the above code, we did not handle the possible exception in method2() method, but threw it to method1().

throw

The throw keyword is different from throws.
The throws keyword means that this method will throw such an exception, while the throw keyword is used in a special statement to indicate that an exception will be thrown.
The code example is as follows:

package workwitherror;

import java.io.FileNotFoundException;

public class Error {
    public static void main(String[] args) {
       try{
           method1();
       }catch(FileNotFoundException e){
           System.out.println("Exception detected!");
       }
    }
    public static void method1()throws FileNotFoundException{
        FileNotFoundException e = new FileNotFoundException();
        throw e;
    }
}
Published 20 original articles, won praise 0, visited 228
Private letter follow

Tags: Java

Posted on Sat, 11 Jan 2020 06:07:46 -0500 by rel