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

解决方案 »

  1.   

    ?????不懂你的意思。。你说的try catch报错,是什么错,是不是就是你的异常啊
      

  2.   

    就是用throws在方法头抛出异常,没有错;用try catch在catch块中处理异常,会有错误(the method must return a result a type of int)
      

  3.   

    和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);
    }
    }
      

  4.   

    1.抓是负责的行为,抓了干嘛还抛。
    2.别抓return  
    真正写代码的时候
    没异常的代码别抓
    抓异常尽量具体点 比如IO异常就抓IOException,别IO异常抓个Exception,影响性能
    而且避免在循环中抓取,有利于性能
      

  5.   

    哥们因为在try{}catch的时候在catch中会处理异常NullpointerException
    在你处理完异常以后,程序会继续往下执行,这个时候结果程序发现,下边没有任何语句,
    更没有返回语句了,咋办?只能报错了
    而throw e是抛出异常,当把NullpointerException抛出后,将不会继续往下执行程序,
    这个时候程序就不会去检查return 的返回值,因为你这个时候的返回值是个异常~~~~~~明白否
    throw e 就是一个返回语句,代替了return的作用,所以抛出异常的时候没问题