异常处理2种方法:
1.抛 (throws) 2.自己处理try/catch/finally
1.抛出:向上一级抛出,异常实际没有被解决掉
2.try/catch/finally
(1)正常执行
public class Test1 {
public static void main(String[] args) {
Test1 test1 = new Test1();
test1.say();
}
public void say() {
String str = "123";
try {
System.out.println(Integer.parseInt(str));
System.out.println("正常执行");
//return;
}catch(Exception e) {
System.out.println("有异常");
//return;
}finally {
System.out.println("finally");
//return;
}
}
}
(2)异常情况:
public class Test1 {
public static void main(String[] args) {
Test1 test1 = new Test1();
test1.say();
}
public void say() {
String str = "abc";
try {
System.out.println(Integer.parseInt(str));
System.out.println("正常执行");
//return;
}catch(Exception e) {
System.out.println("有异常");
//return;
}finally {
System.out.println("finally");
//return;
}
}
}
结论:finally是一定会被执行的!因此,finally通常用于释放资源,在IO流操作和数据库操作中
程序没有报错,执行了 try 和 finally 代码块
程序报错了,执行try catch finally 代码块
那么这里就有一个问题,执行的先后顺序?
这里我们需要连接一个关键字return!
Java中的return有两方面的用途:
(1)返回方法指定类型的值(前提是方法的返回值类型不是void)。
(2)方法的结束,它会导致当前的方法退出。
通过return我们去探究一下,try catch finally的执行先后顺序!
public class Test1 {
public static void main(String[] args) {
Test1 test1 = new Test1();
System.out.println(test1.say());
}
public String say() {
String str = "123";
try {
Integer.parseInt(str);
return "try";
} catch (Exception e) {
return "catch";
} finally {
return "finally";
}
}
}
结果为:finally
public class Test1 {
public static void main(String[] args) {
Test1 test1 = new Test1();
System.out.println(test1.say());
}
public String say() {
String str = "abc";
try {
Integer.parseInt(str);
return "try";
} catch (Exception e) {
return "catch";
} finally {
return "finally";
}
}
}
结果也是finally
这是为什么?finally是必定执行的代码块!所有finally逻辑上虽然能使用return,但一般finally不会接return。否则你什么也测不出来
public class Test1 {
public static void main(String[] args) {
Test1 test1 = new Test1();
System.out.println(test1.say());
}
public String say() {
String str = "abc";
try {
Integer.parseInt(str);
return "try";
} catch (Exception e) {
System.out.println("catch");
return "catch";
} finally {
System.out.println("finally");
}
}
}
由此可以看出执行的顺序为:
(1)Integer.parseInt(str); (2)System.out.println("catch"); (3)System.out.println("finally"); (4)return "catch"; 同理其他:
public class Test1 {
public static void main(String[] args) {
Test1 test1 = new Test1();
System.out.println(test1.say());
}
public String say() {
String str = "abc";
try {
Integer.parseInt(str);
return "try";
} catch (Exception e) {
System.out.println("catch");
return "catch";
} finally {
System.out.println("finally");
return "finally + return";
}
}
}
catch
finally
finally + return
|