java基础 -异常笔记

443,异常处理入门

 

package com.hspedu.exception_;

public class Exception {
    public static void main(String[] args) {
        int num1 = 10;
        int num2 = 0;
        //老韩解读
        //1,num1 / num2 = 10 / 0
        //2,当执行到 num1 / num2,因为 num2 = 0,程序就会出现(抛出)异常 ArithmeticException
        //3,当抛出异常后,程序就退出,崩溃了,下面的代码就不在执行
        //4,大家想想这样的程序好吗?不好,不应该出现了一个不算致命的问题,就导致整个系统崩溃
        //5,java 设计者,提供了一个叫 异常处理机制来解决该问题

        //int res = num1 / num2
        //如果程序员,认为一段代码可能出现异常/问题,可以使用try-catch异常处理机制来解决
        //从而保证程序的健壮性
        //将该该代码块->选中->快捷键 ctrl + alt + t -> 选中 try-catch
        //6,如果进行异常处理,那么即使出现了异常,程序可以继续执行

        try {
            int res = num1 / num2;
        } catch (java.lang.Exception e) {
            //e.printStackTrace();
            System.out.println("出现异常的原因=" + e.getMessage());//输出异常信息
        }

        System.out.println("程序继续运行...");
    }
}

 

444,异常基本介绍

 

 445,异常体系图

 

 

 

446,五大运行时异常

 

(1)NullPointerException空指针异常

 

package com.hspedu.exception_;

public class Exception {
    public static void main(String[] args) {
        String name = null;
        System.out.println(name.length());
    }
}

 

(2)ArithmeticException数学运算异常

 例子在 443节有

 

(3)ArrayIndexOutOfBoundsException数组下标越界异常

 

package com.hspedu.exception_;

public class Exception {
    public static void main(String[] args) {
       int[] arr = {1,2,4};
       for(int i = 0; i <= arr.length; i++)
       {
           System.out.println(arr[i]);
       }
    }
}

 

(4)ClassCastException类型转换异常

 

package com.hspedu.exception_;

public class Exception {
    public static void main(String[] args) {
        A b = new B(); //向上转型
        B b2 = (B)b;//向下转型,这里好着呢
        C c2 = (C)b;//这里抛出ClassCastException
    }
}
class A {}
class B extends A {}
class C extends A {}

 

(5)NumberFormatException数字格式不正确异常

 

package com.hspedu.exception_;

public class Exception {
    public static void main(String[] args) {
        String name = "韩顺平教育";
        //将String 转成 int
        int num = Integer.parseInt(name);//抛出NumberFormatException
        System.out.println(num);
    }
}

 

447,异常课题练习(了解编译异常)

 

448,异常处理机制

 

 

449,try-catch

前3点

 

package com.hspedu.exception_;

public class Exception {
    public static void main(String[] args) {
        //ctrl + alt + t,选中这3行
        try {
            String str = "韩顺平";
            int a = Integer.parseInt(str);
            System.out.println("数字:" + a);
        } catch (NumberFormatException e) {
            System.out.println("异常信息=" + e.getMessage());
        } finally {
            System.out.println("finally代码块被执行...");
        }
        System.out.println("程序继续...");
    }
}

 

第4点

 

package com.hspedu.exception_;

public class Exception {
    public static void main(String[] args) {
        //老韩解读
        //1,如果try代码块有可能有多个异常
        //2,可以使用多个catch 分别捕获不同的异常,相应处理
        //3,要求子类异常写在前面,父类异常写在后面
        try {
            Person person = new Person();
            person = null;
            System.out.println(person.getName()); //NullPointerException
            int n1 = 10;
            int n2 = 0;
            int res = n1 / n2; //ArithmeticException
        } catch (NullPointerException e) { //子类异常
            System.out.println("空指针异常=" + e.getMessage());
        } catch (ArithmeticException e) {
            System.out.println("算术异常=" + e.getMessage());
        } catch (java.lang.Exception e) //父类异常
        {
            System.out.println(e.getMessage());
        } finally {
        }
    }
}
class Person {
    private String name = "jack";

    public String getName() {
        return name;
    }
}

 

第5点

 

package com.hspedu.exception_;

public class Exception {
    public static void main(String[] args) {
        try {
            int n1 = 10;
            int n2 = 0;
            System.out.println(n1 / n2);
        } finally {
            System.out.println("执行了finally...");
        }
        System.out.println("程序继续执行...");
    }
}

 

450,try-catch小结(练习听懂后的)

 

451,try-catch最佳实践

 

package com.hspedu.exception_;

import java.util.Scanner;

public class Exception {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int num = 0;
        String inputStr = "";
        while(true) {
            System.out.println("请输入一个整数:");
            inputStr = scanner.next();
            try {
                num = Integer.parseInt(inputStr);//这里可能抛出异常
                break;
            } catch (NumberFormatException e) {
                System.out.println("你输入的不是一个整数:");
            }
        }
        System.out.println("你输入的值是=" + num);
    }
}

 

452,throws入门案例

 

package com.hspedu.exception_;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Throws {
    public static void main(String[] args) {

    }
    public void f2() throws FileNotFoundException {
        //创建了一个文件流对象
        //老韩解读
        //1,这里的异常是一个FileNotFoundException 编译异常
        //2,使用前面讲过的 try-catch-finally
        //3,使用throws,抛出异常,让调用f2方法的调用者(调用者也是方法)处理
        //4,throws后面的异常类型可以是方法中产生的异常类型,也可以是它的父类Exception
        //5,throws 关键字后也可以是 异常列表,即可以抛出多个异常 FileNotFoundException,NullPointerException,ArithmeticException
        FileInputStream fis = new FileInputStream("d//aa.txt");
    }
}

 

453,throws使用细节

 

第1点和第2点

package com.hspedu.exception_;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Throws {
    public static void main(String[] args) {
        f2();//调用者是main方法,main方法也有默认的throws处理,所以又把异常抛给了JVM处理
    }
    public static void f2() throws ArithmeticException{ //f2方法显式的声明抛出异常,之后该异常由f2方法的调用者处理
        //1,对于编译异常,程序中必须处理,比如 try-catch 或者 throws
        //2,对于运行时异常,程序中如果没有处理,默认就是throws的方式处理
        int n1 = 10;
        int n2 = 0;
        double res = n1 / n2;
    }
}

 

第3点和第4点

package com.hspedu.exception_;
public class Throws {
    public static void main(String[] args) {
    }
}
class Father {//父类
    public void method() throws RuntimeException {
    }
}
class Son extends Father {//子类
    //3,子类重写父类的方法时,对抛出异常的规定:
    //子类重写的方法所抛出的异常类型要么和父类抛出的异常一致,要么为父类抛出的异常类型的子类型
    //4,在throws过程中,如果有方法try-catch,就相当于处理异常,就可以不必throws
    @Override
    public void method() throws ArithmeticException {
    }
}

其他细节点

package com.hspedu.exception_;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class Throws {
    public static void main(String[] args) {

    }
    public static void f1() throws FileNotFoundException {
        //这里大家思考问题 调用f3() 报错
        //老韩解读
        //1,因为f3() 方法抛出的是一个编译异常
        //2,即,这时就要f1() 必须处理这个编译异常
        //3,在f1() 中,要么 try-catch-finally,或者继续throws 这个编译异常
        f3();
    }
    public static void f3() throws FileNotFoundException {
        FileInputStream fis = new FileInputStream("d//aa.txt");
    }
    public static void f4() {
        //老韩解读
        //1,在f4()中调用方法f5() 是好的
        //2,原因是f5() 抛出的是运行异常
        //3,而java中,并不要求程序员显式处理,因为有默认处理机制
        f5();
    }
    public static void f5() throws ArithmeticException{
    }
}

 

454,自定义异常

 

package com.hspedu.exception_;

public class CustomException {
    public static void main(String[] args) {
        int age = 180;
        if(!(age >= 18 && age <= 120)){
            throw new AgeException("年龄需要在 18~120之间");
        }
        System.out.println("你的年龄范围正确");
    }
}
//自定义一个异常
//老韩解读
//1,一般情况下,我们自定义异常是继承 RuntimeException
//2,即把自定义异常做成 运行时异常,好吃是我们可以使用默认的处理机制
//3,即比较方便
class AgeException extends RuntimeException {
    public AgeException(String message) {//构造器
        super(message);
    }
}

 

455,throw和throws区别

 

456,异常课后作业1

 

package com.hspedu.exception_;

import java.util.Scanner;

public class Homework {
    public static void main(String[] args) {
        try {
            //先验证输入的参数的个数是否正确 两个参数
            if(args.length != 2)
            {
                throw new ArrayIndexOutOfBoundsException("参数个数不对");
            }

            //先把接收到的参数,转成整数
            int n1 = Integer.parseInt(args[0]);
            int n2 = Integer.parseInt(args[1]);

            double res = cal(n1, n2); //该方法可能抛出ArithmeticException
            System.out.println("计算结果是=" + res);

        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println(e.getMessage());
        } catch (NumberFormatException e) {
            System.out.println("参数格式不正确,需要输出整数");
        } catch (ArithmeticException e) {
            System.out.println("出现了除0的异常");
        }


    }
    //编写cal方法,就是两个数的商
    public static double cal(int n1,int n2)
    {
        return n1 / n2;
    }
}

 

要配置参数,之前讲过

如果不配置参数,就出现 "参数个数不对"的异常

 运行结果:

 

配置10 hsp 的参数,出现"参数格式不正确,需要输出整数"的异常

 

 

配置 10 0 的参数,出现 "出现了除0的异常"

 

 

posted @ 2024-05-17 19:12  银河小船儿  阅读(22)  评论(0编辑  收藏  举报