关于throw与return的问题

寻川丶 2016-07-21 04:52:32
import java.util.InputMismatchException;
import java.util.Scanner;

public class Test01 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
try{
System.out.println("请输入被除数:");
int num1=sc.nextInt();
System.out.println("请输入除数:");
int num2=sc.nextInt();
System.out.println("两个数相除 结果是:"+num1/num2);
return;
}catch(ArithmeticException ex){
System.out.println("除数不能为0");
}catch(InputMismatchException ex){

System.out.println("您输入的数字 必须是 整数");
}catch(Exception ex){
throw ex;
System.out.println("请联系管理员。。");

}finally{

System.out.println("谢谢使用计算器!");
}


System.out.println("======");


}
}
编译时throw后面那一行报错,请大神帮仔细讲解下
...全文
1028 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
何铁 2016-07-22
  • 打赏
  • 举报
回复
因为你直接throw ex;这个表达你不处理这个异常,直接向外抛出了,而后面的代码因为你直接抛异常停止了虚拟机的运行而无法得到执行,故编译器在编译的时候就告诉你这个是Unreachable code,执行不到的代码。
dzq584462393 2016-07-22
  • 打赏
  • 举报
回复
如果真的发生异常就会 throw ex; //后面的不会执行了,所有会报错 System.out.println("请联系管理员。。");
小灰狼 2016-07-22
  • 打赏
  • 举报
回复
javac 检测到一条不可能被执行的语句 为什么那条语句不可能被执行,楼主自己思考一下
寻川丶 2016-07-21
  • 打赏
  • 举报
回复
引用 2 楼 soton_dolphin 的回复:
[quote=引用 1 楼 soton_dolphin 的回复:] 你只可以throw 新的异常。 throw new Exception("new exception");
throw 后面的程序不会再执行。[/quote] throw只是将异常抛出后不执行后面的程序了吗?就像return那样
soton_dolphin 2016-07-21
  • 打赏
  • 举报
回复
引用 2 楼 soton_dolphin 的回复:
throw 后面的程序不会再执行。
把其他执行语句放到throw 前面。
soton_dolphin 2016-07-21
  • 打赏
  • 举报
回复
引用 1 楼 soton_dolphin 的回复:
你只可以throw 新的异常。 throw new Exception("new exception");
throw 后面的程序不会再执行。
soton_dolphin 2016-07-21
  • 打赏
  • 举报
回复
你只可以throw 新的异常。 throw new Exception("new exception");

62,626

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧