异常处理方式一(try-catch-finally)
1 package com.yhqtv.demo01Exception; 2 /* 3 * 一、异常的处理,抓抛模型 4 * 5 * 过程一:“抛”:程序在正常 执行的过程中,一旦出现异常,就会在异常代码处生成一个对应异常类的对象。 6 * 并将此对象抛出。 7 * 一旦抛出对象以后,其后的代码就不再执行。 8 * 过程二:“抓”,可以理解为异常的处理方式:1 try--ca-finally 2 throws 9 * 10 * 二、try--catch--finally的使用 11 * 12 * try{ 13 * //可能出现异常的代码 14 * }catch(异常类型1 变量名1){ 15 * //处理异常的方式1 16 * }catch(异常类型2 变量名2){ 17 * //处理异常的方式2 18 * } 19 *....... 20 * finally{ 21 * //一定会执行的代码 22 * } 23 * 说明: 24 * 1.finally是可选的。 25 * 2.使用try将可能出现异常代码包装起来,在执行过程中,一旦出现异常,就会生成一个对应异常类的对象,根据此对象 26 * 的类型,去catch中进行匹配 27 * 3.一旦try中的异常对象匹配到某个catch时,就进入catch中进行异常的处理,一旦处理完成,就跳出当前的 28 * try-catch结构(在没有finally的情况),继续执行其后的代码 29 * 4.catch中的异常类型如果没有父子类关系,则谁声明在上,谁声明在下无所谓。 30 * catch中的异常类型如果满足父子类关系,则要求子类一定声明在父类的上面,否则,报错 31 * 5. 常用的异常对象处理的方式:1.String getMessage() 2.printStackTrace() 32 * 6.在try结果中声明的变量,再出了try结构后,就不能再被调用 33 * 7.try-catch-finally结构可以嵌套 34 * 35 * 体会1:使用try-catch-finally处理编译异常时,使得程序在编译时就不再报错,但是运行时仍然可能报错。 36 * 相当于我们使用try-catch-finally将一个编译时可能出现的异常,延迟到运行时出现。 37 * 38 * 体会2:开发中,由于运行时异常比较常见,所以我们通常就不针对运行时异常编写try-catch-finally了。 39 * 针对编译时异常,我们说一定要考虑异常的处理。 40 */ 41 42 import org.junit.Test; 43 44 import java.io.File; 45 import java.io.FileInputStream; 46 import java.io.FileNotFoundException; 47 import java.io.IOException; 48 49 public class ExceptionTest1 { 50 51 52 @Test 53 public void test7() { 54 FileInputStream fis=null; 55 try{ 56 File file = new File("hello.txt"); 57 fis = new FileInputStream(file); 58 59 int data = fis.read(); 60 while (data != -1) { 61 System.out.println((char) data); 62 data = fis.read(); 63 64 } 65 66 }catch (FileNotFoundException e){ 67 e.printStackTrace(); 68 }catch (IOException e){ 69 e.printStackTrace(); 70 }finally { 71 try { 72 if(fis!=null) 73 fis.close(); 74 } catch (IOException e) { 75 e.printStackTrace(); 76 } 77 } 78 79 } 80 81 @Test 82 public void test1() { 83 String str = "123"; 84 str = "abc"; 85 int num = 0; 86 try { 87 num = Integer.parseInt(str); 88 System.out.println("--------1-------"); 89 } catch (NullPointerException e) { 90 System.out.println("出现空指针异常了"); 91 } catch (NumberFormatException e) { 92 // System.out.println("出现数值转换异常了"); 93 //String getMessage(): 94 // System.out.println(e.getMessage()); 95 //printStackTrace(): 96 e.printStackTrace(); 97 } catch (Exception e) { 98 System.out.println("出现异常了"); 99 } 100 101 System.out.println(num); 102 System.out.println("--------3-------"); 103 104 } 105 }
版权声明:本文为yhqtv-com原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。