throws 与 try{ }catch{ }

meacial 2012-08-22 05:54:40
为何抛出异常没有错,而用try catch处理异常会报错
static int method() throws Exception{
try {
int[] a = null;
for (int i = 0; i < a.length; i++) {
System.out.println(i);
}
return 0;
} catch (Exception e) {
throw e;
}
}
--------------------------------------------------------
static int method(){
try {
int[] a = null;
for (int i = 0; i < a.length; i++) {
System.out.println(i);
}
return 0;
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
...全文
121 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
乔梓轩爸爸 2012-08-22
  • 打赏
  • 举报
回复
返回int
千面而一言 2012-08-22
  • 打赏
  • 举报
回复
哥们因为在try{}catch的时候在catch中会处理异常NullpointerException
在你处理完异常以后,程序会继续往下执行,这个时候结果程序发现,下边没有任何语句,
更没有返回语句了,咋办?只能报错了
而throw e是抛出异常,当把NullpointerException抛出后,将不会继续往下执行程序,
这个时候程序就不会去检查return 的返回值,因为你这个时候的返回值是个异常~~~~~~明白否
throw e 就是一个返回语句,代替了return的作用,所以抛出异常的时候没问题
果子狸G 2012-08-22
  • 打赏
  • 举报
回复
1.抓是负责的行为,抓了干嘛还抛。
2.别抓return


真正写代码的时候
没异常的代码别抓
抓异常尽量具体点 比如IO异常就抓IOException,别IO异常抓个Exception,影响性能
而且避免在循环中抓取,有利于性能
游一游走一走 2012-08-22
  • 打赏
  • 举报
回复
和throws没关系,第二处没有返回值

static int method() {
try {
int[] a = null;
for (int i = 0; i < a.length; i++) {
System.out.println(i);
}
return 0;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
meacial 2012-08-22
  • 打赏
  • 举报
回复
就是用throws在方法头抛出异常,没有错;用try catch在catch块中处理异常,会有错误(the method must return a result a type of int)
cnyn 2012-08-22
  • 打赏
  • 举报
回复
?????不懂你的意思。。你说的try catch报错,是什么错,是不是就是你的异常啊

62,614

社区成员

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

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