Java try catch statement

try {
    逻辑代码块1;
} catch(ExceptionType e) {
    处理代码块1;
}

Example 1

import java.util.Scanner;

public class Test02 {
    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);
    }
}
---------学生信息录入---------------
请输入学生姓名:
徐白
请输入学生年龄:
110a
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)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>