Java异常处理总结

╰半夏微凉° 2022-12-27 06:25 313阅读 0赞

文章目录

  • 一. 异常概述
      • 1.1 异常定义
      • 1.2 异常体系结构
  • 二.常见异常
  • 三.异常处理机制 try catch
  • 四. 异常处理机制 try catch
        • finally
  • 五. 异常处理机制 throws
      • 5.2 选择try catch or throws
  • 六. 手动抛出异常 throw
  • 七. 用户自定义异常类
  • 八. 异常练习
  • 九. 总结
      • 常见异常类型
        • 1 NULLPointerException
        • 2 ArrayIndexOutOfBoundsException
        • 3 ClassCastException
        • 4 NUmberFormatException
        • 5 InputMismatchException
        • 6 ArithmeticException

一. 异常概述

输入数据格式
文件是否存在
网络稳定问题

1.1 异常定义

异常:程序中发生的不正常情况
异常分为两类

  1. Error
    JVM无法解决的严重问题:JVM内部错误、资源耗尽
    比如:StackOverflowError 、 OOM
    一般不编写针对性的代码进行处理

    public class ErrorTest {

    1. public static void main(String[] args) {
    2. //TODO 1 StackOverflowError 无限递归
    3. main(args);
    4. //TODO 2 java.lang.OutOfMemoryError 堆溢出
    5. Integer[] arr = new Integer[1024 * 1024 * 1024];
    6. }

    }

  2. Execption
    因编程错误 or 偶然的外在因素导致的一般性问题,可以使用针对性的代码进行处理,例如:

    • 空指针
    • 读取不存在文件
    • 网络中断
    • 数组角标越界

两种解决方法
1 . 遇到错误就i终止
2 . 编写就考虑异常的情况,错误检测 错误消息提示 处理

捕获异常理想是在 编译期间(编译时异常),但有的错误只有在运行时间才会发生(运行时异常)

1.2 异常体系结构

编译的时候不会检查 非受检异常
在这里插入图片描述
在这里插入图片描述

二.常见异常

  1. import java.io.File;
  2. import java.io.FileInputStream;
  3. import java.util.Date;
  4. import java.util.Scanner;
  5. public class ExceptionTest {
  6. /*
  7. * |-----编译时间异常(Checked)
  8. * 在编译时就会报错,不会生成字节码文件
  9. * */
  10. //TODO FileNotFoundException
  11. @Test
  12. public void test7(){
  13. File file = new File("hello.txt");
  14. FileInputStream fileInputStream = new FileInputStream(file);
  15. int data = fileInputStream.read();
  16. while(data != -1){
  17. System.out.println((char)data);
  18. data = fileInputStream.read();
  19. }
  20. fileInputStream.close();
  21. }
  22. /*
  23. * |-----运行时间异常(unChecked / runtimeException)
  24. * */
  25. //TODO 1 NUllPointerException
  26. @Test
  27. public void test1(){
  28. // int[] arr = null;
  29. // System.out.println(arr[3]);
  30. // String str = "abc";
  31. // str = null;
  32. // System.out.println(str.charAt(0));
  33. }
  34. //TODO 2 ArrayIndexOutOfBoundsExcption
  35. @Test
  36. public void test2(){
  37. int arr[] = new int[10];
  38. System.out.println(arr[10]);
  39. String str = "abc";
  40. System.out.println(str.charAt(3));
  41. }
  42. //TODO 3 ClassCastException
  43. @Test
  44. public void test3(){
  45. Object obj = new Date();
  46. String str = (String)obj;
  47. }
  48. //TODO 4 NumberFormatException
  49. @Test
  50. public void test4(){
  51. String str = "123";
  52. str = "abc";
  53. int num = Integer.parseInt(str);
  54. }
  55. //TODO 5 InputMismatchException
  56. @Test
  57. public void test5(){
  58. Scanner scanner = new Scanner(System.in);
  59. String s = scanner.nextLine();
  60. System.out.println(s);//输入一个String
  61. }
  62. //TODO 6 ArithmeticException
  63. @Test
  64. public void test6(){
  65. int a = 2;
  66. int b = 0;
  67. System.out.println(a / b);
  68. }
  69. }

三.异常处理机制 try catch

在编写程序时,经常要在可能出现错误的地方加上检测的代码,如进行x/y运算时,要检测分母为0,数据为空,输入的不是数据而是字符等。过多的if-else分支会导致程序的代码加长、臃肿,可读性差。因此采用异常处理机制。

Java异常处理

Java采用异常处理机制,将异常处理的程序代码集中在一起,与正常程序分开,使得程序简介、优雅、易于维护

1) try catch
2) throws + 异常类型

四. 异常处理机制 try catch

异常处理 :抓抛模型

过程1 抛出
一旦出现异常,就会在异常code处生成一个对应异常类的对象,并将其抛出
一旦抛出异常,其后的code将不再执行

过程2 抓
可以理解为异常的处理方式

  1. try catch finally 的使用
  2. throws

    try{

    1. //可能出现异常的code

    }catch(异常类型1 变量名1){

    1. //处理异常的方式1

    }catch(异常类型2 变量名2){

    1. //处理异常的方式2

    }…
    finally{

    1. //一定会执行的code

    }

Catch规范

catch异常类型都是平行关系 那么谁先谁后都一样 平行关系
cath异常类型如果满足子父类关系,则应该把子类放到前面,否则出错

异常处理的方式

  • String getMessage()
  • printStackTrace()

在try中声明的变量
在出了Try括号之后 ,将不再有效

finally

  1. finally是可选的

    @Test

    1. public void testMethd(){
    2. int num = method();
    3. System.out.println(num);
    4. }
    5. public int method(){
    6. try{
    7. int arr[] = new int[10];
    8. System.out.println(arr[10]);
    9. return 1;
    10. }catch (ArrayIndexOutOfBoundsException e){
    11. e.printStackTrace();
    12. return 2;
    13. }finally {
    14. System.out.println("finally一定指定,其他不一定");
    15. return 3;
    16. }
    17. }

五. 异常处理机制 throws

处理方式二:throws + 异常类型
写在方法声明处,执行此方法时,可能会抛出异常
一旦当方法执行时,出现异常,仍会在异常代码处生成一个异常对象,此对象满足throws后异常类型,就会被抛出
异常代码后续的代码就不再执行!

5.2 选择try catch or throws

  1. 如果父类中被重写的方法没有throws方式处理,子类也不能throws , 必须try catch
  2. 执行的方法A中 先后调用了另外的几个 递进关系的方法 , 递进关系的方法 建议用throws方式,执行的方法A建议用try catch处理

六. 手动抛出异常 throw

关于异常对象的产生

  • 系统自动产生的异常
  • 手动生成的异常对象 并抛出 (throw)

    package com.JavaBase.tarin.d016;

    public class StudentTest{

    1. public static void main(String[] args) {
    2. Student s = new Student();
    3. try {
    4. s.regist(-1001);
    5. } catch (Exception e) {
    6. e.printStackTrace();
    7. System.out.println(e.getMessage());
    8. }
    9. }

    }

    class Student {

  1. private int id;
  2. public void regist(int id) throws Exception {
  3. if(id > 0){
  4. this.id = id;
  5. }else {
  6. // System.out.println("输入非法");
  7. //TODO 手动抛出异常对象
  8. // throw new RuntimeException("输入对象异常!");
  9. throw new Exception("输入对象异常!");
  10. }
  11. }
  12. }

七. 用户自定义异常类

  1. 继承现有异常结构RuntimeException Exception
  2. 提供一个全局常量serialVersionUID 序列号 ,对类的一个标识
  3. 提供重载的构造器

    public class MyException extends RuntimeException{

    1. static final long serialVersionUID = -7034897190745766939L;
    2. public MyException(){
    3. }
    4. public MyException(String msg){
    5. super(msg);
    6. }

    }

八. 异常练习

  1. 编写应用程序EcmDef.java,接收命令行的两个参数,要求不能输入负数,计算
  2. 两数相除。
  3. (NumberFormatException)
  4. (ArrayIndexOutOfBoundsException
  5. 0(ArithmeticException)及输入负数(EcDef 自定义的异常)进行异常处理。
  6. (1)在主类(EcmDef)中定义异常方法(ecm)完成两数相除功能。
  7. (2)在main()方法中使用异常处理语句进行异常处理。
  8. (3)在程序中,自定义对应输入负数的异常类(EcDef)。
  9. (4)运行时接受参数 java EcmDef 20 10 //args[0]=“20” args[1]=“10”
  10. (5)Interger类的static方法parseInt(String s)将s转换成对应的int值。
  11. 如:int a=Interger.parseInt(“314”); //a=314;
  12. package com.JavaBase.tarin.d016;
  13. /*
  14. * 编写应用程序EcmDef.java,接收命令行的两个参数,要求不能输入负数,计算
  15. 两数相除。
  16. 对 数 据 类 型 不 一 致 (NumberFormatException) 、 缺 少 命 令 行 参 数
  17. (ArrayIndexOutOfBoundsException、
  18. 除0(ArithmeticException)及输入负数(EcDef 自定义的异常)进行异常处理。
  19. (1)在主类(EcmDef)中定义异常方法(ecm)完成两数相除功能。
  20. (2)在main()方法中使用异常处理语句进行异常处理。
  21. (3)在程序中,自定义对应输入负数的异常类(EcDef)。
  22. (4)运行时接受参数 java EcmDef 20 10 //args[0]=“20” args[1]=“10”
  23. (5)Interger类的static方法parseInt(String s)将s转换成对应的int值。
  24. 如:int a=Interger.parseInt(“314”); //a=314;
  25. *
  26. * */
  27. public class EcmDev {
  28. public static void main(String[] args) {
  29. try{
  30. int i = Integer.parseInt(args[0]);
  31. int j = Integer.parseInt(args[1]);
  32. int result = ecm(i,j);
  33. }catch (NumberFormatException e){
  34. // e.printStackTrace();
  35. System.out.println("数据类型不一致");
  36. }catch (ArrayIndexOutOfBoundsException e){
  37. // e.printStackTrace();
  38. System.out.println("缺少命令行参数");
  39. }catch (ArithmeticException e){
  40. // e.printStackTrace();
  41. System.out.println("除0");
  42. }catch (EcDef e){
  43. e.printStackTrace();
  44. }
  45. }
  46. public static int ecm(int i ,int j) throws EcDef{
  47. if(i < 0 || j < 0){
  48. throw new EcDef("分子或分母为负数");
  49. }
  50. return i / j;
  51. }
  52. }

九. 总结

在这里插入图片描述

常见异常类型

1 NULLPointerException

空指针异常

  1. //TODO 1 NUllPointerException
  2. @Test
  3. public void test1(){
  4. // int[] arr = null;
  5. // System.out.println(arr[3]);
  6. // String str = "abc";
  7. // str = null;
  8. // System.out.println(str.charAt(0));
  9. }

2 ArrayIndexOutOfBoundsException

数组下标越界异常

  1. public void test2(){
  2. int arr[] = new int[10];
  3. System.out.println(arr[10]);
  4. String str = "abc";
  5. System.out.println(str.charAt(3));
  6. }

3 ClassCastException

类强制转换异常

  1. public void test3(){
  2. Object obj = new Date();
  3. String str = (String)obj;
  4. }

4 NUmberFormatException

数值格式化异常

  1. //TODO 4 NumberFormatException
  2. @Test
  3. public void test4(){
  4. String str = "123";
  5. str = "abc";
  6. int num = Integer.parseInt(str);
  7. }

5 InputMismatchException

输入不匹配 异常

  1. @Test
  2. public void test5(){
  3. Scanner scanner = new Scanner(System.in);
  4. String s = scanner.nextLine();
  5. System.out.println(s);//输入一个String
  6. }

6 ArithmeticException

算数异常

  1. @Test
  2. public void test6(){
  3. int a = 2;
  4. int b = 0;
  5. System.out.println(a / b);
  6. }

发表评论

表情:
评论列表 (有 0 条评论,313人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java异常处理总结

                背景               ![format_png][] 最近专门负责团队的项目质量。我在治理异常日志过程中,总结了一下Java的异常处理。

    相关 异常处理总结

    1. 异常可以分为几类? 答:Java的异常类都是java.lang.Trowable的子类,它派生了两个字类,Error和Exception。前者由系统保留,后者供应用程序