异常处理
[TOC]
Java 的异常处理通过 5 个关键字来实现:try、catch、throw、throws 和 finally。try catch 语句用于捕获并处理异常,finally 语句用于在任何情况下(除特殊情况外)都必须执行的代码,throw 语句用于拋出异常,throws 语句用于声明可能会出现的异常。
try {
// 可能发生异常的语句
} catch(ExceptionType e) {
// 处理异常语句
}
try_catch语句
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)
多重try_catch
public class Test03 {
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;
}
}
输出相应的异常信息方法
- printStackTrace() 方法:指出异常的类型、性质、栈层次及出现在程序中的位置
- getMessage() 方法:输出错误的性质。
- toString() 方法:给出异常的类型与性质。
finally
用finally语句就是将程序,正常最终结束
import java.util.Scanner;
public class Test04 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Windows 系统已启动!");
String[] pros = { "记事本", "计算器", "浏览器" };
try {
// 循环输出pros数组中的元素
for (int i = 0; i < pros.length; i++) {
System.out.println(i + 1 + ":" + pros[i]);
}
System.out.println("是否运行程序:");
String answer = input.next();
if (answer.equals("y")) {
System.out.println("请输入程序编号:");
int no = input.nextInt();
System.out.println("正在运行程序[" + pros[no - 1] + "]");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("谢谢使用!");
}
}
}
结果:
Windows 系统已启动!
1:记事本
2:计算器
3:浏览器
是否运行程序:
y
请输入程序编号:
2
正在运行程序[计算器]
谢谢使用!
//
Windows 系统已启动!
1:记事本
2:计算器
3:浏览器
是否运行程序:
y
请输入程序编号:
5
谢谢使用!
java.lang.ArrayIndexOutOfBoundsException: 4
at text.text.main(text.java:23)
Windows 系统已启动!
1:记事本
2:计算器
3:浏览器
是否运行程序:
asdfasd
谢谢使用!
throw &throws
throws 和throw的区别在于是否需要定声明方法
public class OverrideThrows {
//throws定义在方法后
public void test() throws IOException {
FileInputStream fis = new FileInputStream("a.txt");
}
}
class Sub extends OverrideThrows/*(这里的限制异常超界)*/ {
// 子类方法声明抛出了比父类方法更大的异常
// 所以下面方法出错
public void test() throws Exception {
}
}
throw
import java.util.Scanner;
public class Test05 {
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) {
Test05 te = new Test05();
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);
}
}
}