java零基础Ⅱ-- 3.异常-Exception

连接视频



一、异常的概念

运行下面的代码,看看有什么问题 --> 引出异常和异常处理机制

public static void main(String[] args){
	int num1 = 10;
	int num2 = 0;
	int res = num1 / num2;
	System.out.println("程序继续运行...");
}

在这里插入图片描述

对异常进行捕获,保证程序可以继续执行:try-catch

public class Exception01 {
    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 (Exception e) {
//            e.printStackTrace();
            System.out.println("出现异常的原因=" + e.getMessage());//输出异常信息
        }
        System.out.println("程序继续运行...");
    }
}
==========控制台输出=======
出现异常的原因=/ by zero
程序继续运行...

基本概念

Java语音中,将程序执行中发生的不正确情况称为“异常”。(开发过程中的语法错误和逻辑错误不是异常)


执行过程中所发生的异常事件可分为两大类

  • Error(错误):Java虚拟机无法解决的严重问题。如:JVM 系统内部错误、资源耗尽等严重情况。比如:StackOverflowError【栈溢出】和 OOM (out of memory),Error 是严重错误,程序会崩溃。

  • Exception:其它因编程错误或偶然的外在因素导致的一般性问题,可以使用针对的代码进行处理。例如空指针访问,试图读取不存在的文件,网络连接中断等,Exception 分为两大类:运行时异常[程序运行时,发生的异常] 和 编译时异常[编程时,编译器检查出的异常]。



二、异常的体系图

异常体系图一览

在这里插入图片描述

在这里插入图片描述

异常体系图的小结

1、异常分为两大类,运行时异常编译时异常

2、运行时异常,编译器检查不出来。一般是指编程时的逻辑错误,是程序员应该避免其出现的异常。 java.lang.RuntimeException类及它的子类都是运行时异常

3、对于运行时异常,可以不在处理,因为这类异常很普遍,若全处理可能对程序的可读性和运行效率产生影响

4、编译是异常,是编译器要求必须处置的异常。



三、常见的异常

常见的运行时异常包括

  • 1 NullPointerException 空指针异常
  • 2 ArithmeticException 数学运算异常
  • 3 ArrayIndexOutOfBoundsException 数组下标越界异常
  • 4 ClassCastException 类型转换异常
  • 5 NumberFormatException 数字格式不正确异常

常见的运行时异常举例

1) NullPointerException 空指针异常

当应用程序试图在需要对象的地方使用 null 时,抛出该异常,看案例演示。

在这里插入图片描述

在这里插入图片描述

2)ArithmeticException 数学运算异常

当出现异常的运算条件时,抛出此异常。例如,一个整数“除以零” 时,抛出此类的一个实例,案例演示

在这里插入图片描述

在这里插入图片描述

3)ArrayIndexOutOfBoundsException 数组下标越界异常

用非法索引访问数组时抛出的异常。如果索引为负或大于等于数组大小,则该索引为非法索引。

在这里插入图片描述

在这里插入图片描述

4)ClassCastException 类型转换异常

当试图将对象强制转换为不是实例的子类时,抛出该异常。例如:以下代码将生成一个 ClassCastException

在这里插入图片描述

在这里插入图片描述

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

当应用程序试图将字符串转换成一种数值类型,但该字符不能转换为适当格式时,抛出该异常 => 使用异常我们可以确保输入是满足条件数字。

在这里插入图片描述

在这里插入图片描述



编译异常

介绍

编译异常是指在编译期间,就必须处理的异常,否则代码不能通过编译。

常见的编译异常

  • SQLException:操作数据库时,查询表可能发生的异常
  • IOException:操作文件时,发生的异常
  • FileNotFoundException:当操作一个不存在的文件时,发生的异常
  • ClassNotFoundException:加载类,而该类不存在时,异常
  • EOFException:操作文件,到文件末尾,发生异常
  • IllegalArguementException:参数异常

案例说明

因为我们还没有学习SQL,文件编程等等,这里我们先举例一个(FileNotFoundException)案例来说明,其它异常使用方式类似,演示如下:

//文件操作
FileInputStream fis;
fis = new FileInputStream("d:\\aa.jpg");
int len;
while((len = fis.read()) != -1){
	System.out.println(len);
}
fis.close();

在这里插入图片描述


异常练习

看看下面代码是否正确,为什么?

String frieds[] = {"tom","jack","milan"};
for(int i = 0; i < 4; i++){
	System.out.println(frieds[i]);//
}
//抛出异常:ArrayIndexOutOfBoundsException
public class AAA{
	int x;//默认是0
	public static void main(String[] args){
		int y;
		AAA a = new AAA();
		y = 3 / a.x;//等价于 3 / 0
		System.out.println("program ends ok!");
	}
}
//抛出异常:ArithmeticException
Cat cat = new Cat();
cat = null;
System.out.println(cat.name);
//抛出异常:NullPointerException
class Person{
	public static void main(String[] args){
		Object obj = new Date();
		Person person;
		person = (Peson)obj;//抛出异常
		System.out.println(person);
	}
}
//抛出异常:ClassCastException



四、异常处理概念

基本介绍

异常处理就是当异常发生时,对异常处理的方式。


异常处理的方式

  • 1)try - catch - finally
    程序员在代码块中捕获发生的异常,自行处理
try{
	//代码/可能有异常
}catch(Exception e){
	//1.捕获到异常
	//2.系统将异常封装成 Exception 对象 e,传统给catch
	//3.得到异常对象后,程序员,自己处理
	//4.注意,如果没有发生异常catch代码块不执行
}finally{
	//1.不管try代码块是否有异常发生,始终要执行finally
	//2.所以,通常将释放资源的代码,放在finally
}
  • 2)throws
    将发生的异常抛出,交给调用者(方法)来处理,最顶级的处理者就是JVM

在这里插入图片描述



五、异常处理分类

try-catch 异常处理

try-catch 方式处理异常说明

1)Java提供try和catch块来处理异常。try块用于包含可能出错的代码。catch块用于处理try块中发生的异常。可以根据需要在程序中有多个数量的try…catch块。

2)基本语法

try{
	//可疑代码
	//将异常生成对应的异常对象,传递给catch块
}catch (异常){
	//对异常处理
}
//如果没有finally,语法是可以通过的

try-catch 方式处理异常-快速入门

    public static void main(String[] args) {
        int num1 = 10;
        int num2 = 0;
        try {
            int res = num1 / num2;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

try-catch 方式处理异常 - 注意事项

1)如果异常发生了,则异常发生后面的代码不会执行,直接进入到catch块。

2)如果异常没有发生,则顺序执行try的代码块,不会进入到catch

3)如果希望不管是否发生异常,都执行某段代码(比如关闭连接,释放资源等),则使用如下代码 - finally{}

public class TryCatchDetail {
    public static void main(String[] args) {
        //1.如果异常发生了,则异常发生后面的代码不会执行,直接进入到catch块。
        //2.如果异常没有发生,则顺序执行try的代码块,不会进入到catch
        //3.如果希望不管是否发生异常,都执行某段代码(比如关闭连接,释放资源等),则使用如下代码 - finally
        try {
            String str = "zzp";
            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("程序继续执行...");
    }
}
==========控制台输出=========
异常信息=For input string: "zzp"
finally代码块被执行...
程序继续执行...

4)可以有多个catch语句,捕获不同的异常(进行不同的业务处理),要求父类异常在后,子类异常在前,比如(Exception 在后,NullPointerException 在前),如果发生异常,只会匹配一个catch,演示

public class TryCatchDetail02 {
    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 e1){
            System.out.println("空指针异常=" + e1.getMessage());
        }catch (ArithmeticException e2){
            System.out.println("算术异常=" + e2.getMessage());
        }catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
        }
    }
}
class Person{
    private String name = "jack";

    public String getName() {
        return name;
    }
}

5)可以进行 try - finally 配合使用,这种用法相当于没有捕获异常,因此程序会直接崩掉/退出。应用场景,就是执行一段代码,不管是否发生异常,都必须执行某个业务逻辑

try{
	//代码块..
}finally{ //总是执行
}
public class TryCatchDetail03 {
    public static void main(String[] args) {
        //可以进行 try - finally 配合使用,这种用法相当于没有捕获异常,
        // 因此程序会直接崩掉/退出。应用场景,就是执行一段代码,
        // 不管是否发生异常,都必须执行某个业务逻辑
        try{
            int n1 = 10;
            int n2 = 0;
            int res = n1 / n2;
        }finally{
            System.out.println("执行了finally...");
        }
        System.out.println("程序继续执行...");
    }
}

在这里插入图片描述


try-catch 练习

1、题1

public class Exception01{
    public static int method(){
        try{
            String[] names = new String[3];//String[] 数组 初始值为空
            if(names[1].equals("tom")) {//NullPointerException 异常
                System.out.println(names[1]);
            }else {
                names[3] = "zzp";
            }
            return 1;
        }catch (ArrayIndexOutOfBoundsException e){
            return 2;
        }catch (NullPointerException e){//捕获
            return 3;
        }finally {//必须执行
            return 4;//返回4
        }
    }

    public static void main(String[] args) {
        System.out.println(method());//4
    }
}
//输出什么
4

2、题2

public class Exception02{
    public static int method(){
        int i = 1;
        try{
            i++;//i = 2
            String[] names = new String[3];
            if(names[1].equals("tom")){//空指针异常 
                System.out.println(names[1]);
            }else {
                names[3] = "zzp";
            }
            return 1;
        }catch (ArrayIndexOutOfBoundsException e){
            return 2;
        }catch (NullPointerException e){
            return ++i;//i = 3
        }finally {//必须执行
            return ++i;// i = 4
        }
    }

    public static void main(String[] args) {
        System.out.println(method());//4
    }
}
//输出什么
4

3、题3

public class Exception03{
    public static int method(){
        int i = 1;
        try{
            i++;//i = 2
            String[] names = new String[3];
            if(names[1].equals("tom")){//空指针异常
                System.out.println(names[1]);
            }else {
                names[3] = "zzp";
            }
            return 1;
        }catch (ArrayIndexOutOfBoundsException e){
            return 2;
        }catch (NullPointerException e){
            return ++i;//i = 3 => 保存一个临时变量 temp = 3
        }finally {
            ++i;// i= 4
            System.out.println("i=" + i);// i = 4
        }
    }

    public static void main(String[] args) {
        System.out.println(method());//3
    }
}
//输出什么
i=4
3

try-catch-finally 执行顺序小结

1)如果没有出现异常,则实现try块中使用语句,不执行catch块中语句,如果有finally,最后还需要执行finally里面的语句

2)如果出现异常,则try块中异常发生后,try块剩下的语句不再执行。将执行catch块语句,如果有finally,最后还需要执行finally里面的语句


练习

如果用户输入的不是一个整数,就提示他反复输入,直到输入一个整数为止

public class TryCatchExercise04 {
    public static void main(String[] args) {
        //如果用户输入的不是一个整数,就提示他反复输入,直到输入一个整数为止
        //思路
        //1.创建Scanner对象
        //2.使用无限循环,去接收一个输入
        //3.然后将该输入的值,转成一个int
        //4.如果在转换时,抛出异常,说明输入的内容不是一个可以转成一个int的内容
        //5.如果没有抛出异常,则break 退出循环
        Scanner scanner = new Scanner(System.in);
        int num = 0;
        while (true){
            System.out.println("请输入一个整数:");
            try {
                num = Integer.parseInt(scanner.next());//这里是可能抛出异常
                break;
            } catch (NumberFormatException e) {
                System.out.println("你输入的不是一个整数");
            }
        }
        System.out.println("你输入的值是=" + num);
    }
}



throws 异常处理

基本介绍

1)如果一个方法(中的语句执行时)可能生成某种异常,但是不能确定如何处理这种异常,则此方法显示地声明抛出异常,表明该方法不对这些异常进行处理,而由该方法的调用者负责处理

2)在方法声明中用 throws 语句可以声明抛出异常的列表,throws 后面的异常类型可以是方法中产生的异常类型,也可以是它的父类


快速入门案例

package com.zzpedu.throws_;

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

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

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

注意事项和使用细节

1)对于编译异常,程序中必须处理,比如:try-catch 或者 throws

2)对于运行异常(RuntimeException及其子类),程序中如果没有处理,默认就是 throws 的方式处理

3)子类重写父类的方法时,对抛出的异常的规定:子类重写的方法,所抛出的异常类型要么和父类的异常一致,要么为父类抛出的异常类型的子类型

4)在 throws 过程中,如果有方法 try-catch ,就相当于处理异常,就可以不必 throws

public class ThrowsDetail {
    public static void main(String[] args) {
        f2();
    }
    public static void f2() /* throws ArithmeticException */ {
        //1.对于编译异常,程序中必须处理,比如:try-catch 或者 throws
        //2.对于运行异常,程序中如果没有处理,默认就是 throws 的方式处理
        int n1 = 10;
        int n2 = 0;
        double res = n1 / n2;//抛出异常 默认就是 throws 的方式处理
    }
    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() 是OK的
        //2.原因是f5() 抛出的是运行异常
        //3.而java中,并不要求程序员显示处理,因为有默认处理机制
        f5();
    }
    public static void f5() throws ArithmeticException {

    }

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



六、自定义异常

基本概念

当个程序出现某些 “错误”,但该错误信息并没有在 Throwable 子类中描述处理,这个时候可以自己设计异常,用于描述该错误信息。


自定义异常步骤

1)定义类:自定义异常类名(程序员自己写)继承Exception或者RuntimeException

2)如果继承Exception ,属于编译异常

3)如果继承RuntimeException,,属于运行异常(一般来说,继承RuntimeException)


自定义异常的应用实例

当我们接收Person对象年龄时,要求范围在 18 - 120 之间,否则抛出一个自定义异常(要求 继承RuntimeException),并给出提示信息

package com.zzpedu.customexception_;

public class CustomException {
    public static void main(String[] args) {
        int age = 180;
        //要求范围在 18 - 120 之间,否则抛出一个自定义异常
        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);
    }
}

在这里插入图片描述



七、throw 和 throws 的对比

一览表

意义位置后面跟的东西
throws异常处理的一种方式方法声明处异常类型
throw手动生成异常对象的关键字方法体中异常对象

测试题 - 下面的测试输出什么

class ReturnExceptionDemo{
    static void methodA(){
        try{
            System.out.println("进入方法A");//1
            throw new RuntimeException("制造异常");//3
        }finally {
            System.out.println("用A方法的finally");//2
        }
    }
    static void methodB(){
        try{
            System.out.println("进入方法B");//4
           	return;
        }finally {
            System.out.println("用B方法的finally");//5
        }
    }
}
class ReturnExceptionDemo{
    public static void main(String[] args) {
        try{
            ReturnExceptionDemo.methodA();
        }catch (Exception e){
            System.out.println(e.getMessage());//3
        }
        ReturnExceptionDemo.methodB();
    }
}
//输出内容
//1.进入方法A
//2.用A方法的finally
//3.制造异常
//4.进入方法B
//5.调用B方法的finally
public class ThrowException {
    public static void main(String[] args) {
        try{
            ReturnExceptionDemo.methodA();
        }catch (Exception e){
            System.out.println(e.getMessage());//3
        }
        ReturnExceptionDemo.methodB();
    }
}
class ReturnExceptionDemo{
    static void methodA(){
        try{
            System.out.println("进入方法A");//1
            throw new RuntimeException("制造异常");//3
        }finally {
            System.out.println("用A方法的finally");//2
        }
    }
    static void methodB(){
        try{
            System.out.println("进入方法B");//4
            return;
        }finally {
            System.out.println("用B方法的finally");//5
        }
    }
}
==========控制台输出=====
进入方法AA方法的finally
制造异常
进入方法BB方法的finally



作业

1、编程题

a) 编写应用程序 EcmDef.java ,接收命令行的两个参数(整数),计算两数相除
b) 计算两个数相除,要求使用方法 cal(int n1, int n2)
c) 对数据格式不正确(NumberFormatException)、缺少命令行参数(ArrayIndexOutOfBoundsException),除0 进行异常处理(ArithmeticException)。

public class Homework01 {
    public static void main(String[] args) {
        /*
        a) 编写应用程序 EcmDef.java ,接收命令行的两个参数(整数),计算两数相除
        b) 计算两个数相除,要求使用方法 cal(int n1, int n2)
        c) 对数据格式不正确(NumberFormatException)、缺少命令行参数(ArrayIndexOutOfBoundsException),
            除0 进行异常处理(ArithmeticException)。
         */
        try {
            //先验证输入的参数的个数是否正确 2个
            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;
    }
}

在这里插入图片描述

2、说出下面代码是否会发生异常,如果会,是哪种异常?如果不会,则打印结果是什么

public static void main(String[] args) {
	//args.length = 0
	//这里发生的是 ArrayIndexOutOfBoundsException
    if(args[4].equals("john")){//可能发生空指针异常 NullPointerException
         System.out.println("AA");
     }else {
         System.out.println("BB");
     }
     Object o = args[2];//String -> Object 向上转型
     Integer i = (Integer)o;//错误,这里一定会发生 ClassCastException
}

3、写出程序结果:

public static void func(){//静态方法
	try{
		throw new RuntimeException();
	}finally{
		System.out.println("B");//1
	}
}
public static void main(String[] args) {//mian方法
	try{
		func();
		System.out.println("A");
	}catch(Exception e){
		System.out.println("C");//2
	}
	System.out.println("D");//3
}
//输出结果是
B 
C
D

4、写出程序结果:

public static void main(String[] args) {
	try{
		showExce();
		System.out.println("A");
	}catch(Exception e){
		System.out.println("B");
	}finally{
		System.out.println("C");
	}
	System.out.println("D");
}
public static void showExce() throws Exception{
	throw new Exception();
}
//输出结果是
B 
C
D
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值