读书人

关于throws 跟 try catch

发布时间: 2012-11-09 10:18:48 作者: rapoo

关于throws 和 try catch
1.throws Exception
发生异常,直接抛出,抛出异常后后面的代码不执行

public class Test {
public static void test() throws Exception {
int[] test = new int[10];
test[11] = 10;
}

public static void main(String[] args) throws Exception {

test();

System.out.println("errororrrr");
}
}

输出


Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 11
at Test.test(Test.java:5)
at Test.main(Test.java:10)


2.try-catch
捕获异常后,执行catch语句块,执行完后跳出try语句块,继续执行后面的内容

public class Test {
public static void test() throws Exception {
int[] test = new int[10];
test[11] = 10;
}

public static void main(String[] args) {
try {
test();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("errororrrr");
}
}

输出


java.lang.ArrayIndexOutOfBoundsException: 11
at Test.test(Test.java:4)
at Test.main(Test.java:9)
errororrrr

读书人网 >编程

热点推荐