认识Java中的异常、异常的基本用法

用QQ邮箱发邮件

一、认识异常

1、常见的异常

1.算术异常

System.out.println(10 / 0);
// 执行结果
Exception in thread "main" java.lang.ArithmeticException: / by zero

2.数组下标越界

int[] arr = {
    
    1, 2, 3};
System.out.println(arr[100]);
// 执行结果
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100

3.空指针异常

public class Test {
    
    
	public int num = 10;
	public static void main(String[] args) {
    
    
		Test t = null;
		System.out.println(t.num);
	}
}
// 执行结果
Exception in thread "main" java.lang.NullPointerException

4.Cloneable

class Person implements Cloneable {
    
    
    public int id;

    @Override
    protected Object clone() throws CloneNotSupportedException {
    
    
        return super.clone();
    }
}

public class TestDemo {
    
    
    public static void main(String[] args) throws CloneNotSupportedException {
    
    
        Person person = new Person();
        Person person1 = (Person) person.clone();
    }
}

2、防御式编程

错误在代码中是客观存在的,因此我们要让程序出现问题的时候及时通知程序猿。我们有两种主要的方式

LBYL: Look Before You Leap. 在操作之前就做充分的检查

EAFP: It’s Easier to Ask Forgiveness than Permission. " 事后获取原谅比事前获取许可更容易". 也就是先操作,遇到问题再处理

异常的核心思想就是 EAF


3、异常的好处

例如, 我们用伪代码演示一下开始一局王者荣耀的过程

LBYL 风格的代码(不使用异常)

boolean ret = false;
ret = 登陆游戏();
if (!ret) {
    
    
	处理登陆游戏错误;
	return;
}
ret = 开始匹配();
if (!ret) {
    
    
	处理匹配错误;
	return;
}
ret = 游戏确认();
if (!ret) {
    
    
	处理游戏确认错误;
	return;
}
ret = 选择英雄();
if (!ret) {
    
    
	处理选择英雄错误;
	return;
}
ret = 载入游戏画面();
if (!ret) {
    
    
	处理载入游戏错误;
	return;
}

EAFP 风格的代码(使用异常)

try {
    
    
	登陆游戏();
	开始匹配();
	游戏确认();
	选择英雄();
	载入游戏画面();
	...
} catch (登陆游戏异常) {
    
    
	处理登陆游戏异常;
} catch (开始匹配异常) {
    
    
	处理开始匹配异常;
} catch (游戏确认异常) {
    
    
	处理游戏确认异常;
} catch (选择英雄异常) {
    
    
	处理选择英雄异常;
} catch (载入游戏画面异常) {
    
    
	处理载入游戏画面异常;
}

第一种方式,正常流程和错误处理流程代码混在一起,代码整体显的比较
混乱,而第二种方式正常流程和错误流程是分离开的,更容易理解代码


二、异常的基本用法

1、捕获异常

try 代码块中放的是可能出现异常的代码
catch 代码块中放的是出现异常后的处理行为
finally 代码块中的代码用于处理善后工作, 会在最后执行
其中 catch 和 finally 都可以根据情况选择加或者不加

在这里插入图片描述


catch 可以有多个

当try中发生了异常后,要在对应的catch里,捕获对应的异常,
如果没有不糊该异常,就会交给JVM处理,程序终止

public class TestDemo {
    
    
    public static void main(String[] args) {
    
    
        int[] array = {
    
    1,2,3};
        try{
    
    
            array = null; // 修改代码, 让代码抛出的是空指针异常
            System.out.println(array[5]);
        }catch (ArrayIndexOutOfBoundsException e){
    
    
            e.printStackTrace();
            System.out.println("捕捉到一个数组越界异常!");
        } catch (NullPointerException e) {
    
    
            e.printStackTrace();
            System.out.println("捕捉到一个空指针异常!");
        }
        System.out.println("xxx");
    }
}

可以简化成一个catch:

public class TestDemo {
    
    
    public static void main(String[] args) {
    
    
        int[] array = {
    
    1,2,3};
        try{
    
    
            array = null; // 修改代码, 让代码抛出的是空指针异常
            System.out.println(array[5]);
        }catch (ArrayIndexOutOfBoundsException | NullPointerException e){
    
    
            e.printStackTrace();
            System.out.println("捕捉到一个数组越界异常!");
        }
        System.out.println("xxx");
    }
}

2、Java 异常体系

  • 顶层类 Throwable 派生出两个重要的子类, Error 和 Exception
  • 其中 Error 指的是 Java 运行时内部错误和资源耗尽错误. 应用程序不抛出此类异常. 这种内部错误一旦出现,除了告知用户并使程序终止之外, 再无能无力. 这种情况很少出现.
  • Exception 是我们程序猿所使用的异常类的父类.
  • 其中 Exception 有一个子类称为 RuntimeException , 这里面又派生出很多我们常见的异常类NullPointerException , IndexOutOfBoundsException 等
  • Java语言规范将派生于 Error 类或 RuntimeException 类的所有异常称为 非受查异常, 所有的其他异常称为 受查异常.
    显式处理的方式有两种: (见第6点)
    a) 使用 try catch 包裹起来
    b) 在方法上加上异常说明, 相当于将处理动作交给上级调用者
    在这里插入图片描述

栈溢出错误:

public class TestDemo {
    
    
    public static void func() {
    
    
        func();
    }
    public static void main(String[] args) {
    
    
        func();
    }
}

// 执行结果:
Exception in thread "main" java.lang.StackOverflowError

在这里插入图片描述

可以用一个 catch 捕获所有异常(不推荐)

  • 由于 Exception 类是所有异常类的父类。因此可以用这个类型表示捕捉所有异常
    备注:catch 进行类型匹配的时候,不光会匹配相同类型的异常对象, 也会捕捉目标异常类型的子类对象
    如刚才的代码,NullPointerException 和 ArrayIndexOutOfBoundsException 都是 Exception 的子类,因此都能被捕获到
  • 但是父类异常不能放在子类异常上面
int[] arr = {
    
    1, 2, 3};
try {
    
    
	System.out.println("before");
	arr = null;
	System.out.println(arr[100]);
	System.out.println("after");
} catch (Exception e) {
    
     // 
	e.printStackTrace();
}
System.out.println("after try catch");

// 执行结果
before
java.lang.NullPointerException
at demo02.Test.main(Test.java:12)
after try catch

3、 finally

最后的善后工作, 例如释放资源

finally 执行的时机是在方法返回之前(try 或者 catch 中如果有 return 会在这个 return 之前执行 finally). 但是如果finally 中也存在 return 语句, 那么就会执行 finally 中的 return, 从而不会执行到 try 中原有的 return.
一般我们不建议在 finally 中写 return (被编译器当做一个警告).

public class TestDemo {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        try {
    
    
            int n = scanner.nextInt();
            System.out.println(10/n);
        }catch (InputMismatchException e) {
    
    
            e.printStackTrace();
            System.out.println("输入有误!");
        }catch (ArithmeticException e) {
    
    
            e.printStackTrace();
            System.out.println("算术异常,可能0作为了除数");
        }finally {
    
     //一般用作 资源的关闭
            scanner.close();
            System.out.println("finally执行了!");
        }
    }
}

使用 try 负责回收资源
刚才的代码可以有一种等价写法, 将 Scanner 对象在 try 的 ( ) 中创建, 就能保证在 try 执行完毕后自动调用 Scanner的 close 方法
把光标放在 try 上悬停, 会给出原因. 按下 alt + enter

public class TestDemo {
    
    
    public static void main(String[] args) {
    
    
        try (Scanner scanner = new Scanner(System.in)) {
    
    
            int n = scanner.nextInt();
            System.out.println(10 / n);
        } catch (InputMismatchException e) {
    
    
            e.printStackTrace();
            System.out.println("输入有误!");
        } catch (ArithmeticException e) {
    
    
            e.printStackTrace();
            System.out.println("算术异常,可能0作为了除数");
        } finally {
    
     //一般用作 资源的关闭
            System.out.println("finally执行了!");
        }
    }
}

4、异常处理流程

  • 程序先执行 try 中的代码
  • 如果 try 中的代码出现异常, 就会结束 try 中的代码, 看和 catch 中的异常类型是否匹配.
  • 如果找到匹配的异常类型, 就会执行 catch 中的代码
  • 如果没有找到匹配的异常类型, 就会将异常向上传递到上层调用者.
  • 无论是否找到匹配的异常类型, finally 中的代码都会被执行到(在该方法结束之前执行).
  • 如果上层调用者也没有处理的了异常, 就继续向上传递.
  • 一直到 main 方法也没有合适的代码处理异常, 就会交给 JVM 来进行处理, 此时程序就会异常终止

异常长会沿着 异常的信息调用栈 进行传递:

public class TestDemo {
    
    
    public static void func(int n) {
    
    
        /*try{
            System.out.println(10/n);
        }catch (ArithmeticException e) {
            e.printStackTrace();
        }*/
        System.out.println(10/n);
    }

    public static void main(String[] args) {
    
    
        try {
    
    
            func(0);
        }catch (ArithmeticException e) {
    
    
            e.printStackTrace();
        }
    }
}

5、抛出异常 throw

除了 Java 内置的类会抛出一些异常之外, 程序猿也可以手动抛出某个异常. 使用 throw 关键字完成这个操作

用 throws 关键字, 把可能抛出的异常显式的标注在方法定义的位置. 从而提醒调用者要注意捕获这些异常

	public static void func(int x) throws RuntimeException{
    
     // 声明
        if(x == 0) {
    
    
            throw new RuntimeException("x==" +x); // 抛出自定义的异常:
        }
    }

6、显式处理的方式

Java语言规范将派生于 Error 类或 RuntimeException 类的所有异常称为 非受查异常, 所有的其他异常称为 受查异常.
显式处理的方式有两种:

在这里插入图片描述

a) 使用 try catch 包裹起来

public class TestDemo {
    
    
    public static void main(String[] args) throws FileNotFoundException {
    
    
        System.out.println(readFile());
    }
    public static String readFile() throws FileNotFoundException {
    
    
        // 尝试打开文件, 并读其中的一行.
        File file = new File("e:/test.txt");
        // 使用文件对象构造 Scanner 对象.
        Scanner sc = new Scanner(file);
        return sc.nextLine();
    }
}

b) 在方法上加上异常说明, 相当于将处理动作交给上级调用者

public class TestDemo {
    
    
    public static void main(String[] args) {
    
    
        System.out.println(readFile());
    }
    public static String readFile() {
    
    
        // 尝试打开文件, 并读其中的一行.
        File file = new File("e:/test.txt");
        // 使用文件对象构造 Scanner 对象.
        Scanner sc = null;
        try {
    
    
            sc = new Scanner(file);
        } catch (FileNotFoundException e) {
    
    
            e.printStackTrace();
        }
        return sc.nextLine();
    }
}

三、自定义异常类

Java 中虽然已经内置了丰富的异常类, 但是我们实际场景中可能还有一些情况需要我们对异常类进行扩展, 创建符合我们实际情况的异常.

  • 注意:如果继承Exception就是受查异常
    而如果继承RuntimeException就是非首查异常:
//受查异常
class MyException extends Exception{
    
    

}
//非受查异常
class MyException2 extends RuntimeException{
    
    

}
  1. 受查异常:try catch 或 加异常说明
//受查异常
class MyException extends Exception{
    
    
    public MyException(String message) {
    
    
        super(message);
    }
}

public class Test {
    
    
    public static void func1(int x) {
    
    
        try {
    
    
            if(x == 0) {
    
    
                throw new MyException("heihei");
            }
        }catch (MyException e) {
    
    
            e.printStackTrace();
        }
    }

    public static void func2(int x) throws MyException{
    
    
        if(x == 0) {
    
    
            throw new MyException("hahah");
        }
    }
}
  1. 非受查异常:
//非受查异常
class MyException2 extends RuntimeException{
    
    
    public MyException2(String message) {
    
    
        super(message);
    }
}

public class Test {
    
    
    public static void func3(int x) throws MyException{
    
    
        try {
    
    
            if(x == 0) {
    
    
                throw new MyException2("heihei");
            }
        }catch (MyException2 e) {
    
    
            e.printStackTrace();
        }
    }

    public static void func4(int x) {
    
    
        // JVM 处理
        if(x == 0) {
    
    
            throw new MyException2("heihei");
        }
    }
}

实现一个用户登陆功能:

class NameException extends RuntimeException {
    
    
    public NameException(String message) {
    
    
        super(message);
    }
}

class PasswordException extends RuntimeException {
    
    
    public PasswordException(String message) {
    
    
        super(message);
    }
}

public class TestDemo {
    
    
    private static final String name = "bit";
    private static final String password = "123";

    public static void login(String name,String password) throws  NameException,PasswordException{
    
    
        if(!TestDemo.name.equals(name)) {
    
    
            throw new NameException("用户名错误");
        }
        if(!TestDemo.password.equals(password)) {
    
    
            throw new PasswordException("密码错误!");
        }
    }
    public static void main(String[] args) {
    
    
        try {
    
    
            login("bit","1234");
        }catch (NameException e) {
    
    
            System.out.println("用户名错误了!");
        }catch (PasswordException e) {
    
    
            e.printStackTrace();
            System.out.println("密码错误了!");
        }finally {
    
    
            System.out.println("finally执行了!");
        }
    }
}

练习1:
编写一个类,在其main()方法的try块里抛出一个Exception类的对象。传递一个字符串参数给Exception的构造器。在catch子句里捕获此异常对象,并且打印字符串参数。添加-一个finally子句,打印一条信息以证明这里确实得到了执行。

	public static void main2(String[] args) {
    
    
        try {
    
    
            throw new Exception("我抛出异常了!");
        }catch (Exception e) {
    
    
            e.printStackTrace();
        }finally {
    
    
            System.out.println("我finally确实被执行了");
        }
    }

练习2:
使用while循环建立类似“恢复模型”的异常处理行为,它将不断重复,直到异常不再抛出。

    public static void main(String[] args) {
    
    
        int i = 0;
        while(i < 10) {
    
    
            try {
    
    
                if(i < 10) {
    
    
                    throw new Exception();
                }
            }catch (Exception e) {
    
    
                e.printStackTrace();
                System.out.println("尝试链接网络第 "+i+"次………………");
                i++;
            }
        }
        System.out.println("链接恢复,程序继续执行!");
    }

JAVA37 判断学生成绩

添加链接描述

描述
定义一个方法用于录入学生的考试成绩,要求考试成绩必须在0-100之间,不满足就产生一个自定义异常,控制台输出一个错误信息"分数不合法"(请输出自定义异常对象的错误信息,将错误信息设置为分数不合法)
输入描述:
控制台输入的int类型整数
输出描述:
若分数合法则输出该分数,否则输出错误信息分数不合法
示例1
输入:100
输出:100
示例2
输入:-1
输出:分数不合法

import java.util.*;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        int score = scanner.nextInt();

        //write your code here......
        try {
    
    
            if(score >= 0 && score <=  100) {
    
    
                System.out.println(score);
            }else {
    
    
                throw new ScoreException("分数不合法");
            }
        }catch (ScoreException e) {
    
    
            // e.printStackTrace();
            System.out.println(e.getMessage());
        }
    }
}

class ScoreException extends Exception {
    
    
    
    //write your code here......
    public ScoreException(String message) {
    
    
        super(message);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_56884023/article/details/121515452
今日推荐