标签:
1 import java.io.File; 2 import java.io.FileInputStream; 3 import java.io.FileNotFoundException; 4 import java.io.IOException; 5 import java.util.Date; 6 import java.util.InputMismatchException; 7 import java.util.Scanner; 8 9 import org.junit.Test; 10 11 12 public class TestException1 { 13 // 编译时异常 14 @Test 15 public void test6() { 16 FileInputStream fis = null; 17 try { 18 fis = new FileInputStream(new File("hello.txt")); 19 int b; 20 while ((b = fis.read()) != -1) { 21 System.out.print((char) b); 22 } 23 24 } catch (FileNotFoundException e1) { 25 System.out.println("文件找不到了!"); 26 } catch (IOException e1) { 27 System.out.println(e1.getMessage()); 28 } finally { 29 try { 30 fis.close(); 31 } catch (IOException e) { 32 // TODO Auto-generated catch block 33 e.printStackTrace(); 34 } 35 } 36 } 37 38 // 常见的运行时异常 39 // 4.空指针异常:NullPointerExcetion 40 @Test 41 public void test5() { 42 // Person p = new Person(); 43 // p = null; 44 // System.out.println(p.toString()); 45 46 try { 47 String str = new String("AA"); 48 str = null; 49 System.out.println(str.length()); 50 } catch (Exception e) { 51 // e.printStackTrace(); 52 System.out.println("出现空指针的异常了"); 53 } 54 } 55 56 // 3.类型转换异常:ClassCastException 57 @Test 58 public void test4() { 59 try { 60 Object obj = new Date(); 61 String str = (String) obj; 62 } catch (ClassCastException e) { 63 System.out.println("出现类型转换的异常了"); 64 //System.out.println(10 / 0); 65 } catch (Exception e) { 66 e.printStackTrace(); 67 } finally { 68 System.out.println("hello!美女!"); 69 } 70 // String str1 = (String)new Date(); 71 } 72 73 // 2.算术异常:ArithmeticException 74 @Test 75 public void test3() { 76 try { 77 int i = 10; 78 System.out.println(i / 0); 79 } catch (Exception e) { 80 // e.printStackTrace(); 81 System.out.println(e.getMessage()); 82 } 83 } 84 85 // 1.数组下标越界的异常:ArrayIndexOutOfBoundsException 86 @Test 87 public void test2() { 88 try { 89 int[] i = new int[10]; 90 // System.out.println(i[10]); 91 System.out.println(i[-10]); 92 } catch (Exception e) { 93 System.out.println("出现异常了!"); 94 } 95 } 96 97 @Test 98 public void test1() { 99 Scanner s = new Scanner(System.in); 100 try { 101 int i = s.nextInt(); 102 System.out.println(i); 103 } catch (InputMismatchException e) { 104 System.out.println("出现类型不匹配的异常了!"); 105 } 106 } 107 }
标签:
原文地址:http://www.cnblogs.com/zhangfan94/p/4263322.html