
1、try...catch...finally
把可能出现异常的地方放在try代码块内,在后面接上catch处理对应的异常,一个try可以有多个catch子句(不能存在子类关系)用于捕获不同的异常。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public static void main(String[] args){
try {
int sum = 0;
}
catch (Exception err){
System.out.println(err.getMessage());
}
finally {
System.out.println( "do the close operate" );
}
}
|
2、try-with-resource
在try代码块运行结束之后,资源会被自动关闭,而对于这种操作也可以有catch和finally子句,这些子句会在资源关闭后执行。
1 2 3 4 5 6 7 8 9 10 11 12 13 | public static void main(String[] args){
try ( var in = new Scanner( new FileInputStream( "I:/javastudy/demo.txt" ), StandardCharsets.UTF_8)){
while ( in .hasNext()){
System.out.println( in .next());
}
}
catch (Exception err){
System.out.println(err.getMessage());
}
}
|
以上就是Java捕获异常的两种方法,希望对大家有所帮助。更多Java学习指路:Java基础
本教程操作环境:windows7系统、java10版,DELL G3电脑。