这是编译时异常和运行时异常的区别导致的.
IOException 是一种【编译时异常】:是Exception的子类, 在编译时期必须处理.
所以 方法y,需要 在方法定义时thorws IOException或者使用try catch捕获.
这就是方法y 报错的原因.
修改方法1:
public void y() throws IOException{ // 调用y方法时, 还需要处理这个异常
throw new IOException("Exception from y");
}
修改方法2
public void y() {
try {
throw new IOException("Exception from y");
} catch (IOException e) {// 捕获到异常后,在catch代码里处理
//..处理异常
e.printStackTrace();
}
}
RuntimeException 【运行时异常】它的所有子类,也是运行时异常.
运行时异常的特点:
RuntimeException 无须显式声明抛出 .
RuntimeException 方法定义时无需throws声明, 也可以不使用try catch捕获. 即 在编译时期可以选择处理或者不处理
调用时也无需处理该异常
方法无需thorws声明
public void x() throws RuntimeException { // throws RuntimeException 可以不写
throw new RuntimeException("Exception from x");
}
代码块也不需要try catch捕获
public void x() {
try { // try catch可以不用
throw new RuntimeException("Exception from x");
} catch (RuntimeException e) {
}
}
常见的 运行时异常有很多..
比如 当 10/0 时 , 会抛出java.lang.ArithmeticException:除0错误
数组下标越界异常
int[] ary =new int[]{-2}; //只有一个元素 ,下标是0
System.out.println(ary[9]);//ArrayIndexOutOfBoundsException
空指针异常
int[] ary=null;
System.out.println(ary.length); //NullPointerException
数字格式异常
String str = "abc";
int num = Integer.parseInt(str);//NumberFormatException
例子: 比如要求用户输入一行字符串, 我们需要把字符串转换为整数. 如果不能转为整数,那么就要求用户重新输入一行字符串.
import java.util.Scanner;
public class RTException {
// 说明. 判断用户的输入是否符合要求,使用正则表达式会更优雅
// 但是这段代码,主要目的是弄清楚try catch的执行
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num ;
while(true) {
System.out.println("请输入一个整数");
String line = sc.nextLine();
try {
num = Integer.parseInt(line);//用于如果输入不是整数,那么代码不能向下继续执行,而是跳进catch里进行处理
break;//如果代码能进行到这里,那么说明用户的输入是整数, 跳出while循环
}catch (NumberFormatException e) {
System.out.println("Sorry,输入错误~!");
continue;
}
}
System.out.println("输入成功!!!数字是"+num);
}
}
上面代码的测试如下
请输入一个整数
abc
Sorry,输入错误~!
请输入一个整数
风云
Sorry,输入错误~!
请输入一个整数
16
输入成功!!!数字是16