首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

throws 与 try{ }catch{ },该如何处理

2012-09-05 
throws 与 try{ }catch{ }为何抛出异常没有错,而用try catch处理异常会报错static int method() throws Ex

throws 与 try{ }catch{ }
为何抛出异常没有错,而用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());
}
}

[解决办法]
?????不懂你的意思。。你说的try catch报错,是什么错,是不是就是你的异常啊
[解决办法]
和throws没关系,第二处没有返回值

Java code
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);        }    }
[解决办法]
1.抓是负责的行为,抓了干嘛还抛。
2.别抓return


真正写代码的时候
没异常的代码别抓
抓异常尽量具体点 比如IO异常就抓IOException,别IO异常抓个Exception,影响性能
而且避免在循环中抓取,有利于性能
[解决办法]
哥们因为在try{}catch的时候在catch中会处理异常NullpointerException
在你处理完异常以后,程序会继续往下执行,这个时候结果程序发现,下边没有任何语句,
更没有返回语句了,咋办?只能报错了
而throw e是抛出异常,当把NullpointerException抛出后,将不会继续往下执行程序,
这个时候程序就不会去检查return 的返回值,因为你这个时候的返回值是个异常~~~~~~明白否
throw e 就是一个返回语句,代替了return的作用,所以抛出异常的时候没问题
[解决办法]
返回int

热点排行
Bad Request.