异常的第二种处理方法:消极处理,使用throws关键字
使用场景:如果一个方法中的语句执行时可能生成某种异常,但是并不能确定如何
处理,则可以在程序所在的函数声明后,使用throws关键字抛出异常
用throws声明方法抛出异常,不进行处理。谁调用谁负责处理
–
覆盖方法抛出异常时,可以抛出与被覆盖方法相同的异常或者被覆盖方
法异常的子类异常。
throws抛出异常写法:
public static void testThrows() throws //抛出的异常类型(可跟多个异常,用,分隔){
//检测异常的语句
}
throw
异常是通过关键字
throw
抛出,程序可以用throw语句引发明确的异常。
throw抛出异常语句:
void doA() throws Exception1 {try {……} catch(Exception1 e) {throw e;//再次抛出} catch(Exception2 e) {System.out.println(" 出错了 ");}
实例:
package com.neuedu.test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.logging.Logger;
public class TestCatch {
static Logger log=Logger.getLogger("com.neuedu.test.TeatCatch");
//不处理异常:throws
public static void testThrows() throws ClassNotFoundException, FileNotFoundException{
Class.forName("java.util.Map");
FileInputStream fis=new FileInputStream("D:\\HelloWorld.java");
}
public static int testReturn()
{
int tmp=0;
try {
//假设以下代码执行占用了很多资源,那么即使抛了异常,我们也希望把占用的资源给释放掉
Class.forName("java.util.Map");
FileInputStream fis=new FileInputStream("D:\\HelloWorld.java");
//return tmp;
}
catch (FileNotFoundException|ClassNotFoundException e) {
e.printStackTrace();
tmp=1;
return tmp;
//System.out.println("释放资源"); 这里不行
}finally{ //这个语句块可以有,也可以没有 需要进行释放资源等必须的操作时才写
System.out.println("释放资源");
}
tmp=2;
return tmp;
}
public static void main(String[] args) throws ClassNotFoundException, FileNotFoundException {
testThrows();
int a=testReturn();
System.out.println(a);
}
}