1.当发生异常的时候,try里的代码还能执行吗?catch里的代码呢?其他的代码呢?
(1)当发生异常的时候,在try代码块中捕捉异常,异常代码发生行之后的代码不再运行。
(2)在catch中的代码,只要没有发生异常,都会运行完毕的。
(3)try…catch之后的代码也会在没有异常的情况下正常执行。
示例代码:
package cn.com;
public class CatchTest {
public static void main(String[] args) {
try {
System.out.println("try代码块:我是异常发生前的代码,正在执行。。。");
System.out.println(1/0);
System.out.println("try代码块:我是异常发生后的代码,正在执行。。。");
} catch (Exception e) {
e.printStackTrace();
System.out.println("catch代码块:我是异常发生后的代码,正在执行。。。");
}
System.out.println("try...catch之外的代码,正在执行。。。");
}
}
运行结果(Console:):
try代码块:我是异常发生前的代码,正在执行。。。
java.lang.ArithmeticException: / by zero
at cn.com.CatchTest.main(CatchTest.java:9)
catch代码块:我是异常发生后的代码,正在执行。。。
try...catch之外的代码,正在执行。。。
2.使用try…catch和在方法上抛出异常的区别是什么?
(1)try…catch是在当前方法内解决掉异常,try…catch之外的代码依然会执行,如果有返回值,会正常返回。
(2)在方法上throws抛出异常,相当于把整个方法作为一个try…catch块,如果发生异常,此方法中异常代码发生行之后的所有代码都不会再运行,当被调用时,调用者必须使用try…catch处理异常或者throws抛出异常。
代码示例(try…catch):
package cn.com;
public class ReturnTest {
public static void main(String[] args) {
ReturnTest test = new ReturnTest();
String result = "main方法中默认值";
try{
result = test.strReturn();
}catch(Exception e){
e.printStackTrace();
}
System.out.println("返回值:" + result);
}
public String strReturn(){
String str = "strReturn()中默认值";
try{
int a = (1 / 0);
return str;
}catch(Exception e){
e.printStackTrace();
}
str = "strReturn()中修改过的值";
return str;
}
}
运行结果(Console:):
java.lang.ArithmeticException: / by zero
at cn.com.ReturnTest.strReturn(ReturnTest.java:16)
at cn.com.ReturnTest.main(ReturnTest.java:7)
返回值:strReturn()中修改过的值
结果说明在strReturn()方法中,try…catch代码块之后的代码正常运行,并正常执行return返回了修改过后的str。
代码示例(throws):
package cn.com;
public class ReturnTest {
public static void main(String[] args) {
ReturnTest test = new ReturnTest();
String result = "main方法中默认值";
try{
result = test.strReturn();
}catch(Exception e){
e.printStackTrace();
}
System.out.println("返回值:" + result);
}
public String strReturn(){
String str = "strReturn()中默认值";
int a = (1 / 0);
str = "strReturn()中修改过的值";
return str;
}
}
运行结果(Console:):
java.lang.ArithmeticException: / by zero
at cn.com.ReturnTest.strReturn(ReturnTest.java:15)
at cn.com.ReturnTest.main(ReturnTest.java:7)
返回值:main方法中默认值
结果分析:在strReturn()方法中,发生异常后的代码不再执行,即使有return语句,该语句也不执行。
3.当方法有返回值时,发生异常,return语句会执行吗?
示例同标题2。
如本博客有错误的地方,欢迎留言指出!谢谢。