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

浙公网安备 33010602011771号