日期:2014-05-20  浏览次数:20811 次

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