throw 和 throws
throw | throws |
---|---|
生成并抛出异常 | 声明方法内抛出了异常 |
位于方法体内部,可作为单独语句使用 | 必须跟在方法参数列表后面,不能单独使用 |
抛出一个异常对象,且只能是一个 | 声明抛出异常类型,可以跟多个异常 |
实例代码
public void testThrows() throws Exception {
throw new Exception("测试异常");
}
try-catch-finally 异常捕获
try-catch-finally结构中try语句块是必须的,catch、finally语句块均可选,但两者至少出现之一。
finally 里面的代码是否发生异常都会执行。
try-catch块中存在return语句,是否还执行finally块?
实例代码如下
public static int test2() {
int a = 10;
try {
a++;
System.out.println(a/0);
System.out.println("try 里面的代码块 a=" + a);
return a;
} catch (Exception e) {
a++;
System.out.println("catch 里面的代码块 a=" + a);
return a;
}finally {
a++;
System.out.println("finally 里面的代码块 a=" + a);
return a;
}
}
// 运行顺序和结果如下
catch 里面的代码块 a=12
finally 里面的代码块 a=13
test2的返回值:13
try 中的打印 a 值得语句没有执行,因为a/0发生异常下面代码没有执行
try-catch-finally块中,finally块唯一不执行的情况是什么?
当finally 前面的代码调用System.exit(1);后,finally块不在执行
public static int test2() {
int a = 10;
try {
a++;
System.out.println(a/0);
} catch (Exception e) {
a++;
System.out.println("catch 里面的代码块 a=" + a);
System.exit(1);
}finally {
a++;
System.out.println("finally 里面的代码块 a=" + a);
}
return a;
}
// 运行顺序和结果如下
catch 里面的代码块 a=12