异常抛出和捕获

 1 import java.io.*; 
3
public class Test { 4 public static void main(String[] args){ 5 try { 6 test2(); 7 } catch (Exception e) { 8 e.printStackTrace(); 9 } 10 } 11 static void test() throws Exception{ 12 throw new Exception("test"); 13 } 14 static void test1(){ 15 try { 16 throw new Exception("test1"); 17 } catch (Exception e) { 18 e.printStackTrace(); 19 } 20 } 21 /** 22 * static void test(){ //方法没有显示声明(throws)会抛出异常 23 * throw new Exception("test");//单独抛出异常,必须捕获 try - catch。 24 * } 25 */ 26 static void test2() throws Exception{ 27 28 } 29 }
 1 import java.io.*; 
3
public class Test { 4 public static void main(String[] args){ 5 try { 6 test(); 7 } catch (Exception e) { 8 e.printStackTrace(); 9 } 10 11 try { 12 test1();//此处出现错误因为IOException是Exception的子类, 13 //test1()可能抛出的Exception无法捕获 14 } catch (IOException e) { 15 e.printStackTrace(); 16 } 17 } 18 static void test() throws IOException{ 19 20 } 21 static void test1() throws Exception{ 22 23 } 24 }

 

posted @ 2013-11-15 16:15  soul390  阅读(182)  评论(0)    收藏  举报