深刻理解try,catch,finally,throws,throw五个关键字
上面咱们来看一下异样机制中五个关键字的用法以及须要留神的中央。
1.try,catch,finally
try关键字用来突围可能会出现异常的逻辑代码,它独自无奈应用,必须配合catch或者finally应用。Java编译器容许的组合应用模式只有以下三种模式:
try...catch...; try....finally......; try....catch...finally...
当然catch块能够有多个,留神try块只能有一个,finally块是可选的(然而最多只能有一个finally块)。
三个块执行的程序为try—>catch—>finally。
当然如果没有产生异样,则catch块不会执行。然而finally块无论在什么状况下都是会执行的(这点要十分留神,因而局部状况下,都会将开释资源的操作放在finally块中进行)。
在有多个catch块的时候,是依照catch块的先后顺序进行匹配的,一旦异样类型被一个catch块匹配,则不会与前面的catch块进行匹配。
在应用try..catch..finally块的时候,留神千万不要在finally块中应用return,因为finally中的return会笼罩已有的返回值。上面看一个例子:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Main {
public static void main(String[] args) { String str = new Main().openFile(); System.out.println(str); } public String openFile() { try { FileInputStream inputStream = new FileInputStream("d:/a.txt"); int ch = inputStream.read(); System.out.println("aaa"); return "step1"; } catch (FileNotFoundException e) { System.out.println("file not found"); return "step2"; }catch (IOException e) { System.out.println("io exception"); return "step3"; }finally{ System.out.println("finally block"); //return "finally"; }}
}
这段程序的输入后果为:
能够看出,在try块中产生FileNotFoundException之后,就跳到第一个catch块,打印"file not found"信息,并将"step2"赋值给返回值,而后执行finally块,最初将返回值返回。