Java throws和throw

statement throws an exception

When an abnormality occurs a method of treatment it is not, then declare the exception of the head of the process, in order to pass the exception of the method of processing to the outside. Use of the method throws statement indicates that this method does not handle exceptions. throws the following format:

returnType method_name(paramList) throws Exception 1,Exception2,…{…}

Wherein, returnType represents a return type; method_name name representation; paramList parameter indicative list; Exception 1, Exception2, ... represents exception class.

If there are multiple exception classes, separated by commas. These exception classes may be called the method will throw an exception is generated, the body may be a method for generating and thrown.

Use throws that throw the exception idea is that the current method does not know how to handle this type of exception that should be handled by the caller's upper level; if the main method does not know how to handle this type of exception, can use throws a statement exception is thrown, the exception to the JVM process. JVM processing method is abnormal, print stack trace of the exception, and the program run aborted.

Create a readFile () method, which is used to read the contents of the file, in the process of reading may produce an IOException, but without any treatment in this method, an exception to the caller and the process may occur . Try catch to catch exceptions using the main () method, and outputs the abnormality information. code show as below:

import java.io.FileInputStream;
import java.io.IOException;

public class Test {
    public void readFile() throws IOException {
        // 定义方法时声明异常
        FileInputStream file = new FileInputStream("read.txt"); // 创建 FileInputStream 实例对象
        int f;
        while ((f = file.read()) != -1) {
            System.out.println((char) f);
            f = file.read();
        }
        file.close();
    }

    public static void main(String[] args) {
        Throws t = new Test();
        try {
            t.readFile(); // 调用 readFHe()方法
        } catch (IOException e) {
            // 捕获异常
            System.out.println(e);
        }
    }
}

The above code, first used in the definition of readFile when () method throws an exception keyword statement that may arise in the process, and then call readFile () method main () method, and use the catch statement to catch exceptions generated.

When the method declaration throws an exception override the limits of
using statement throws an exception is thrown when there is a limit, it is a method of rewriting rules: the exception type subclass method declaration should be thrown exception types thrown by the parent class method declaration or the same sub-class, sub-class method declaration throws an exception thrown permitted to declare multi abnormal than the parent class method . See the following procedure.

public class OverrideThrows {
    public void test() throws IOException {
        FileInputStream fis = new FileInputStream("a.txt");
    }
}

class Sub extends OverrideThrows {
    // 子类方法声明抛出了比父类方法更大的异常
    // 所以下面方法出错
    public void test() throws Exception {
    }
}

The above procedure Sub subclass test () method declaration throws Exception, which is the parent Exception class declaration throws an exception IOException parent class, which will cause the program will not compile.

So when writing code for class inheritance to note that the subclass when the parent class method with a throws clause rewritten, the subclass method declaration throws clause can not be the father throws clause of the corresponding method appears abnormal types do not have, Therefore throws clause can restrict the behavior of the subclass. In other words, the subclass method throws an exception can not exceed the scope of the parent class definition.

throw an exception is thrown

The difference is that the throws, the throw statement is used to directly throw an exception, followed by a thrown exception class objects, syntax is as follows:

throw ExceptionObject;

Wherein, ExceptionObject must be an object class or subclass of Throwable . If a custom exception class Throwable must also be direct or indirect subclass. For example, the following statement will produce syntax errors at compile time:

throw new String("拋出异常");    // String类不是Throwable类的子类

When the throw statement is executed, it will not execute the following statements, then the program branches to the caller program, to find matched catch phrase, executes the corresponding exception handler. If the matching catch clause is found, the program calls up sub-layer. Thus up layer by layer, until the outermost exception handler terminates the program and print a case where the call stack.

throw keywords are not used alone, its use is fully compliant with the exception handling mechanism, but, in general, users are avoiding abnormal, it will not be thrown by hand a new instance of the exception class, and often throws examples of abnormality in a program that has been produced.

In a warehouse management system, required by the user name of the administrator needs more than eight letters or numbers, can not contain other characters. When the length of 8 bits or less thrown exception, and displays the abnormality information; when the character containing the non-letters or numbers, the same exception is thrown, the display abnormality information. code show as below:

import java.util.Scanner;

public class Test {
    public boolean validateUserName(String username) {
        boolean con = false;
        if (username.length() > 8) {
            // 判断用户名长度是否大于8位
            for (int i = 0; i < username.length(); i++) {
                char ch = username.charAt(i); // 获取每一位字符
                if ((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
                    con = true;
                } else {
                    con = false;
                    throw new IllegalArgumentException("用户名只能由字母和数字组成!");
                }
            }
        } else {
            throw new IllegalArgumentException("用户名长度必须大于 8 位!");
        }
        return con;
    }

    public static void main(String[] args) {
        Test te = new Test();
        Scanner input = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String username = input.next();
        try {
            boolean con = te.validateUserName(username);
            if (con) {
                System.out.println("用户名输入正确!");
            }
        } catch (IllegalArgumentException e) {
            System.out.println(e);
        }
    }
}

As the above code, the validateUserName () method throws an IllegalArgumentException exception of two, i.e. when a user name or a numeric character and non-alpha containing less than 8 bits length. In the main () method, call the validateUserName () method, and use the catch phrase to capture this method may throw an exception.

Running the program, when the user name of the user input comprises a non-numeric letters or characters, the program outputs an abnormality, as shown below.

请输入用户名:
admqanistrator@#
java.lang.IllegalArgumentException: 用户名只能由字母和数字组成!

When the user inputs a user name length is less than 8 bits, the program will output the same abnormality, as shown below.

请输入用户名:
admin
java.lang.IllegalArgumentException: 用户名长度必须大于 8 位!
Several differences between throws and throw keywords on the keywords used are as follows:

. 1 throws to declare a method might throw all exception information, the possibility of abnormal said, but not necessarily the occurrence of these anomalies; throw it refers to a specific type of exception thrown, the throw execution certainly throws some kind of exception object.

2. Throws typically by the method declaration (s) may be thrown exception information in a process (class) of the declaration, the declaration and the internal through a throw exception information specific method (s).

. 3 throws are usually not explicitly catch the exception, by the system will automatically capture all the anomalies thrown superior method; throw it require the user to capture relevant exceptions, and then its related packaging, and finally throw the exception information package out.

Published 457 original articles · won praise 94 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_45743799/article/details/104737081