用QQ邮箱发邮件
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();
}
}
错误在代码中是客观存在的,因此我们要让程序出现问题的时候及时通知程序猿。我们有两种主要的方式
LBYL: Look Before You Leap. 在操作之前就做充分的检查
EAFP: It’s Easier to Ask Forgiveness than Permission. " 事后获取原谅比事前获取许可更容易". 也就是先操作,遇到问题再处理
异常的核心思想就是 EAF
例如, 我们用伪代码演示一下开始一局王者荣耀的过程
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 (载入游戏画面异常) {
处理载入游戏画面异常;
}
第一种方式,正常流程和错误处理流程代码混在一起,代码整体显的比较
混乱,而第二种方式正常流程和错误流程是分离开的,更容易理解代码
try 代码块中放的是可能出现异常的代码
catch 代码块中放的是出现异常后的处理行为
finally 代码块中的代码用于处理善后工作, 会在最后执行
其中 catch 和 finally 都可以根据情况选择加或者不加
当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");
}
}
栈溢出错误:
public class TestDemo {
public static void func() {
func();
}
public static void main(String[] args) {
func();
}
}
// 执行结果:
Exception in thread "main" java.lang.StackOverflowError
可以用一个 catch 捕获所有异常(不推荐)
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
最后的善后工作, 例如释放资源
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执行了!");
}
}
}
异常长会沿着 异常的信息调用栈 进行传递:
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();
}
}
}
除了 Java 内置的类会抛出一些异常之外, 程序猿也可以手动抛出某个异常. 使用 throw 关键字完成这个操作
用 throws 关键字, 把可能抛出的异常显式的标注在方法定义的位置. 从而提醒调用者要注意捕获这些异常
public static void func(int x) throws RuntimeException{ // 声明
if(x == 0) {
throw new RuntimeException("x==" +x); // 抛出自定义的异常:
}
}
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 中虽然已经内置了丰富的异常类, 但是我们实际场景中可能还有一些情况需要我们对异常类进行扩展, 创建符合我们实际情况的异常.
//受查异常
class MyException extends Exception{
}
//非受查异常
class MyException2 extends RuntimeException{
}
//受查异常
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");
}
}
}
//非受查异常
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("链接恢复,程序继续执行!");
}
添加链接描述
描述
定义一个方法用于录入学生的考试成绩,要求考试成绩必须在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);
}
}