Java try catch statement Detailed

In practical applications, is extremely important for handling errors of any program difficult to achieve hundred percent perfect, there may be a lot of unknown problems in the program, so be sure to various issues appropriate treatment program development, and Java exception handling mechanism provided can help the user to better solve this problem. Java exception handling mechanism allows the program has excellent fault tolerance, make the program more robust.

Java exception handling is achieved through five keywords: try, catch, throw, throws, and finally. try catch statement is used to catch and handle an exception, finally statement for the code (except in special circumstances) must be carried out under any circumstances, throw statement to throw an exception, throws statement is used to declare an exception may occur.

In Java usually try catch statement to catch the exception and handle. Syntax is as follows:

try {
    // 可能发生异常的语句
} catch(ExceptionType e) {
    // 处理异常语句
}

In the above syntax, the package may raise an exception statement in the try block to capture the exception may occur. After the catch (Exception class) put matching catch clause specifies the type of exception process can generate exception class object instance when an abnormality occurs.

If an exception occurs in the try block, then the object is a corresponding exception will be thrown, will then catch statement depending on the type of the exception object is thrown capture and processing. After processing, the program will skip the rest of the try block statement, a block statement to catch behind the first statement begins execution.

If the try block no abnormality occurs, the normal end of the try block, the rear catch block is skipped, the program will catch the first statement after the block statement begins execution.

note: Try ... catch and if ... else not the same, the latter try braces {} can not be omitted, even though only one line of code in try block, the braces can not be omitted. Similarly is the catch block after the braces {} may not be omitted. Further, the variable declared try block only the local variable within the code block, only valid within the try block, other parts can not access the variable.

In the above processing block syntax may be output corresponding to the abnormality information by using the following three methods.

	printStackTrace() 方法:指出异常的类型、性质、栈层次及出现在程序中的位置。
	
	getMessage() 方法:输出错误的性质。
	
	toString() 方法:给出异常的类型与性质。

Entry to write a student's name, age and gender of the program, the request can not capture the digital age, is the exception. As used herein, the statement to try catch achieved, as follows:

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("---------学生信息录入---------------");
        String name = ""; // 获取学生姓名
        int age = 0; // 获取学生年龄
        String sex = ""; // 获取学生性别
        try {
            System.out.println("请输入学生姓名:");
            name = scanner.next();
            System.out.println("请输入学生年龄:");
            age = scanner.nextInt();
            System.out.println("请输入学生性别:");
            sex = scanner.next();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("输入有误!");
        }
        System.out.println("姓名:" + name);
        System.out.println("年龄:" + age);
    }
}

The code in main () method try catch statement to catch exceptions, the exception may occur age = scanner.nextlnt (); code in the try block, specified in the capture catch statement exception type Exception, and call the exception object printStackTrace () method output exception information. Run results are shown below.

---------学生信息录入---------------
请输入学生姓名:
张伟
请输入学生年龄:
120a
java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
输入有误!
姓名:张伟
年龄:0
    at text.text.main(text.java:19)

Multiple catch statements

If the try block, there are many statements exception occurs, an exception occurs and the type and number. You can try later with a plurality of catch block. Multi catch block syntax is as follows:

try {
    // 可能会发生异常的语句
} catch(ExceptionType e) {
    // 处理异常语句
} catch(ExceptionType e) {
    // 处理异常语句
} catch(ExceptionType e) {
    // 处理异常语句
...
}

In the case where a plurality of catch blocks, when a catch block to an exception, the other catch block will no longer match.

note: When there is a plurality of parent-child relationship between the exception trapping, to capture when capturing the general exception subclass, recapture the parent class. So a subclass must be abnormal in the parent class before, otherwise subclass not catch.

public class Test {
    public static void main(String[] args) {
        Date date = readDate();
        System.out.println("读取的日期 = " + date);
    }

    public static Date readDate() {
        FileInputStream readfile = null;
        InputStreamReader ir = null;
        BufferedReader in = null;
        try {
            readfile = new FileInputStream("readme.txt");
            ir = new InputStreamReader(readfile);
            in = new BufferedReader(ir);
            // 读取文件中的一行数据
            String str = in.readLine();
            if (str == null) {
                return null;
            }
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            Date date = df.parse(str);
            return date;
        } catch (FileNotFoundException e) {
            System.out.println("处理FileNotFoundException...");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("处理IOException...");
            e.printStackTrace();
        } catch (ParseException e) {
            System.out.println("处理ParseException...");
            e.printStackTrace();
        }
        return null;
    }
}

The code O (Input Output) technique stream read by the Java I / readme.txt string from the file, and then be parsed date. Because Java I / O technology has not been introduced, we do not focus on the first I / O technical details, you can look at the method call exception when they happened.

In the try block of code line 12 to call the constructor FileInputStream FileNotFoundException exception may occur. 16, line of code calls readLine BufferedReader input stream () method of an IOException may occur. IOException, FileNotFoundException exception subclass should first capture FileNotFoundException exception, see the code on line 23; after capturing an IOException, see line 26 of code.

If FileNotFoundException IOException and capture order transposing, the capture FileNotFoundException exception will never enter the block, FileNotFoundException exception handler is never executed. The code at line 29 with the exception ParseException IOException FileNotFoundException and parent-child relationship is not abnormal, the abnormal point can be placed to capture ParseException freely.

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

Guess you like

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