TRY里面有RETURN语句

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

java中异常处理中return的用法关于try、catch、finally语句块中含有return语句的几点说明:

1、第一种情况:try块有return语句,catch块没有return,函数末尾也没有return:

看代码:

import java.util.*;

public class demo{

public static void main(string args[]){

int num = 10;

test(num);

}

public static int test(int b){

try{

b += 10;

return b;

}catch(exception e){

}finally{

}

}

}

编译结果:

h:\java demo>javac demo.java

demo.java:18: 缺少返回语句

}

^

1 错误

有人可能会说,我在try块中不是有return语句吗?为什么会提示缺少return语句呢?这是因为编译器认为try块中是又可能产生异常操作

的,也就是说在return语句之前如果出现异常的话,那么return语句根本没有机会得到执行,所以编译器会认为缺少return语句。

解决办法:a、在catch块中加入return语句,因为一旦出现异常,catch中的语句可以保证函数会有一个返回值

b、在finally块中加入return语句,同样只要系统不退出,finally语句块会始终得到执行的

代码:

import java.util.*;

public class demo{

public static void main(string args[]){

int num = 10;

system.out.println(test(num));

}

public static int test(int b){

try{

b += 10;

return b;

}catch(exception e){

}finally{ return 0;

}

}

}

c、在函数末尾加入return语句

代码:

import java.util.*;

public class demo{

public static void main(string args[]){

int num = 10;

system.out.println(test(num));

}

public static int test(int b){ try{

b += 10;

return b;

}catch(exception e){

}finally{

}

return 0;

}

}

2、第二种情况,看代码:

import java.util.*;

public class demo{

public static void main(string args[]){

int num = 10;

system.out.println(test(num));

}

public static int test(int b){

try{

b += 10;

}

return 0;

}

}

结果:h:\java demo>javac demo.java

demo.java:8: try 不带有 catch 或 finally

try{

^

1 错误

说明:也就是说,如果有try语句的话,可以有catch语句,没有finally语句,但是如果没有catch语句的话,那么一定要有finally语句

。并且如果出现catch语句的话,catch语句可以出现多次,而finally语句只能出现

一次。

代码:

public class demo{

public static void main(string args[]){

int num = 10;

system.out.println(test(num));

}

public static int test(int b){ try{

b += 10;

}catch(runtimeexception e){

}catch(exception e2){

}finally{

}

return 0;

}

}

3、第三种情况:

a、try块中有return语句,那么是先执行return语句,还是先执行finally语句。大家通常会有一个错误的认识,可能有的老师都会讲错

,认为是先执行finally语句,再执行return语句,但是这是错误的,事实上是先执行return语句,再执行finally语句,然后将结果返回,也可以说return语句执行了两次,一次在finally之前,一次在finally之后,但是返回的确是第一次执行的值,如果有不信的,请继续看代码,此段代码可以证明我的观点:

代码:

public class demo{

public static void main(string args[]){

int num = 10;

system.out.println(test(num));

}

public static int test(int b){

try{

b += 10;

return b;

}catch(runtimeexception e){

}catch(exception e2){ }finally{

b += 10;

}

return 0;

}

}

结果:

h:\java demo>javac demo.java

h:\java demo>java demo 20

说明:此处需要引入缓冲的概念,有对缓冲不太了解的也没关系,程序运行结果是20

相关文档
最新文档