Java笔记
第十一章、异常(Exception)
11.1、异常处理入门(P444)
1、
package com.hspedu.exception_;
/**
* @author wxb
* @version 1.0
* creat 2024-02-26-19:10
*/
public class Exception01 {
public static void main(String[] args) {
int num1 = 10;
int num2 = 0;
int res = num1 / num2;//由于num2为0,程序会抛出异常
System.out.println("程序继续执行...");
}
}
2、
package com.hspedu.exception_;
/**
* @author wxb
* @version 1.0
* creat 2024-02-26-19:10
*/
public class Exception01 {
public static void main(String[] args) {
int num1 = 10;
int num2 = 0;
//当抛出异常后,程序就退出(崩溃了),下面的代码也不会再执行
//这样的程序不好,不应该因为一个不算致命的错误,就导致整个程序崩溃
//Java的设计者提供了一个叫 异常处理机制 来解决这个问题
//int res = num1 / num2;//由于num2为0,程序会抛出异常
//如果程序员认为一段代码可能出现异常,可以使用try-catch异常处理机制来解决
//从而保证程序的健壮性
//下面代码快捷键:选中一段代码 ctrl + alt + t,然后再选择try/catch
try {
int res = num1 / num2;
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("程序继续执行...");
}
}
3、
package com.hspedu.exception_;
/**
* @author wxb
* @version 1.0
* creat 2024-02-26-19:10
*/
public class Exception01 {
public static void main(String[] args) {
int num1 = 10;
int num2 = 0;
//当抛出异常后,程序就退出(崩溃了),下面的代码也不会再执行
//这样的程序不好,不应该因为一个不算致命的错误,就导致整个程序崩溃
//Java的设计者提供了一个叫 异常处理机制 来解决这个问题
//int res = num1 / num2;//由于num2为0,程序会抛出异常
//如果程序员认为一段代码可能出现异常,可以使用try-catch异常处理机制来解决
//从而保证程序的健壮性
//下面代码快捷键:选中一段代码 ctrl + alt + t,然后再选择try/catch
try {
int res = num1 / num2;
} catch (Exception e) {
//e.printStackTrace();
System.out.println(e.getMessage());//输出异常信息
}
System.out.println("程序继续执行...");
}
}
11.2、异常基本介绍(P445)
-
基本概念
java语言中,将程序执行中发生的不正常的情况称为"异常"。(开发过程中的语法错误和逻辑错误不是异常)
-
执行过程中所发生的异常事件可分为两类
1、Error(错误):Java虚拟机无法解决的严重问题。如:JVM系统内部错误、资源耗尽等严重情况。比如:StackOverflowError[栈溢出]和OOM(out of memory),Error是严重错误,程序会崩溃。
2、Exception:其它因编程错误或偶然的外在因素导致的一般性问题,可以使用正对型代码进行处理。例如空指针访问,试图读取不存在的文件,网络连接中断等等,Exception分为两大类:运行时异常[]和编译时异常[]
11.3、异常体系图(P446)
-
异常体系图一览
-
异常体系图的小结
1、异常分为两大类,运行时异常和编译时异常
2、运行时异常,编译器检查不出来。一般是指编程时的逻辑错误,是程序员应该避免其出现的异常。java.lang.RuntimeException类及它的子类都是运行时异常
3、对于运行时异常,可以不做处理,因为这类异常很普通,若全部处理可能会对程序的可读性和运行效率产生影响
4、编译时异常,是编译器要求必须处置的异常
11.4、五大运行时异常(P447)
-
常见的运行时异常
1、NullPointerException 空指针异常
当应用程序试图在需要对象的地方使用null时,抛出该异常。
package com.hspedu.exception_;
/**
* @author wxb
* @version 1.0
* creat 2024-02-27-20:05
*/
public class NullPointerException_ {
public static void main(String[] args) {
String name = null;
System.out.println(name.length());
}
}
输出结果为:
Exception in thread "main" java.lang.NullPointerException
at com.hspedu.exception_.NullPointerException_.main(NullPointerException_.java:11)
2、ArithmeticException 数字运算异常
当出现运算条件的异常时,抛出此异常。例如,一个数除以 0 时
package com.hspedu.exception_;
/**
* @author wxb
* @version 1.0
* creat 2024-02-27-20:07
*/
public class ArithmeticException_ {
public static void main(String[] args) {
int num1 = 5;
int num2 = 0;
System.out.println(num1 / num2);
}
}
输出结果为:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.hspedu.exception_.ArithmeticException_.main(ArithmeticException_.java:12)
3、ArrayIndexOutOfBoundsException 数组下标越界异常
用非法索引访问数组时抛出的异常。如果索引为负或大于等于数组大小,则该索引为非法索引
package com.hspedu.exception_;
/**
* @author wxb
* @version 1.0
* creat 2024-02-27-20:17
*/
public class ArrayIndexOutOfBoundsException_ {
public static void main(String[] args) {
int arr[] = {12, 3, 4, 5, 5};
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
System.out.println(arr[5]);
}
}
输出结果为:
12
3
4
5
5
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at com.hspedu.exception_.ArrayIndexOutOfBoundsException_.main(ArrayIndexOutOfBoundsException_.java:14)
4、ClassCastException 类型转换异常
当试图将对象强制转换为不是实例的子类时,抛出该异常。
package com.hspedu.exception_;
/**
* @author wxb
* @version 1.0
* creat 2024-02-27-21:02
*/
public class ClassCastException_ {
public static void main(String[] args) {
A a = new B();//向上转型
B b = (B) a;//向下转型
C c = (C) a;//这里抛出异常ClassCastException;a已经被转为B类,而B类与C类没有任何关系
}
}
class A {
}
class B extends A {
}
class C extends A {
}
输出结果为:
Exception in thread "main" java.lang.ClassCastException: com.hspedu.exception_.B cannot be cast to com.hspedu.exception_.C
at com.hspedu.exception_.ClassCastException_.main(ClassCastException_.java:12)
5、NumberFormatException 数字格式不正确异常[]
当应用程序试图将字符串转换成以中国数值类型,但该字符串不能转换为适当格式时,抛出该异常 => 使用异常我们可以确保输入是满足条件数字
package com.hspedu.exception_;
/**
* @author wxb
* @version 1.0
* creat 2024-02-27-21:05
*/
public class NumberFormatException_ {
public static void main(String[] args) {
String name = "1a";
int num = Integer.parseInt(name);
System.out.println(num);
}
}
输出结果为:
Exception in thread "main" java.lang.NumberFormatException: For input string: "1a"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at com.hspedu.exception_.NumberFormatException_.main(NumberFormatException_.java:11)
11.5、异常课堂练习(P448)
-
介绍
编译异常是指在编译期间,就必须处理的异常,否则代码不能通过编译。
-
常见的编译异常
1、SQLException:操作数据库时,查询表可能发生异常
2、IOException:操作文件时,发生的异常
3、FileNotFoundException:当操作一个不存在的文件时,发生异常
4、ClassNotFoundException:加载类,而该类不存在时,发生异常
5、EOFException:操作文件,到文件末尾,发生异常
6、IIIegalArguementException:参数异常
-
看下面代码是否正确
1、下标越界
package waste;
/**
* @author wxb
* @version 1.0
* creat 2024-02-27-20:17
*/
public class Waste_1 {
public static void main(String[] args) {
String friends[] = {"tom", "jack", "milan"};
for (int i = 0; i < 4; i++) {
System.out.println(friends[i]);
}
}
}
输出结果为:
tom
jack
milan
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at waste.Waste_1.main(Waste_1.java:12)
2、数字运算异常
package waste;
/**
* @author wxb
* @version 1.0
* creat 2024-02-27-20:17
*/
public class Waste_1 {
int x;//默认为0
public static void main(String[] args) {
//2
int y;
Waste_1 waste_1 = new Waste_1();
y = 3 / waste_1.x;
System.out.println("program ens ok!");
}
}
输出结果为:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at waste.Waste_1.main(Waste_1.java:21)
3、空指针
package waste;
/**
* @author wxb
* @version 1.0
* creat 2024-02-27-20:17
*/
public class Waste_1 {
int x;//默认为0
public static void main(String[] args) {
Car car = new Car();
car = null;
System.out.println(car.name);
}
}
class Car {
public String name = "123";
}
输出结果为:
Exception in thread "main" java.lang.NullPointerException
at waste.Waste_1.main(Waste_1.java:27)
4、类型转换异常
package waste;
/**
* @author wxb
* @version 1.0
* creat 2024-02-27-20:17
*/
public class Waste_1 {
int x;//默认为0
public static void main(String[] args) {
Object o = new Object();
Waste_1 waste_1;
waste_1 = (Waste_1) o;//这里抛出异常
System.out.println(waste_1);
}
}
输出结果为:
Exception in thread "main" java.lang.ClassCastException: java.lang.Object cannot be cast to waste.Waste_1
at waste.Waste_1.main(Waste_1.java:32)
11.6、异常处理机制(P449)
-
基本介绍
异常处理就是当异常发生时,对异常处理的方式
-
异常处理的方式
1、try-catch-finally
程序员在代码中捕获发生的异常,自行处理
2、throws
将发生的异常抛出,交给调用者(方法)来处理,最顶级的处理者就是JVM
11.7、try-catch(P450)
-
try-catch方式处理异常说明
1、java提供try和catch块来处理异常。try块用于包含可能出错的代码。catch块用于处理try块中发生的异常。可以根据需要在程序中设有多个try-catch块
2、基本语法
try {
//可能报异常代码
//将异常生成对应的异常对象,传递给catch块
} catch {
//对异常的处理
}
//如果没有finally,语法是可以通过的
-
try-catch方式处理异常 - 注意事项
1、如果发生了异常,则发生异常的后面的代码不会执行,直接进入到catch块
package com.hspedu.try_;
/**
* @author wxb
* @version 1.0
* creat 2024-02-28-9:49
*/
public class TryCatchDetail {
public static void main(String[] args) {
try {
String str = "abc";
int a = Integer.parseInt(str);//这行代码发生异常,下面代码不会再执行
System.out.println("数字" + a);
} catch (NumberFormatException e) {
System.out.println("异常信息 = " + e.getMessage());
}
}
}
输出结果为:
异常信息 = For input string: "abc"
2、如果异常没有发生,则顺序执行try的代码块,不会进入到catch
package com.hspedu.try_;
/**
* @author wxb
* @version 1.0
* creat 2024-02-28-9:49
*/
public class TryCatchDetail {
public static void main(String[] args) {
//如果try代码块没有异常发生,则顺序执行try的代码块,不会进入到catch
try {
String str = "123";
int a = Integer.parseInt(str);
System.out.println("数字" + a);
} catch (NumberFormatException e) {
System.out.println("异常信息 = " + e.getMessage());
}
}
}
输出结果为:
数字123
3、如果希望不管是否发生异常,都执行某段代码(比如关闭连接,释放资源等),则使用代码-----> try-catch-finally
①没有异常发生
package com.hspedu.try_;
/**
* @author wxb
* @version 1.0
* creat 2024-02-28-9:49
*/
public class TryCatchDetail {
public static void main(String[] args) {
//如果try代码块没有异常发生,则顺序执行try的代码块,不会进入到catch
try {
String str = "123";
int a = Integer.parseInt(str);
System.out.println("数字" + a);
} catch (NumberFormatException e) {
System.out.println("异常信息 = " + e.getMessage());
} finally {
System.out.println("finally代码块被执行...");
}
}
}
输出结果为:
数字123
finally代码块被执行...
②发生异常
package com.hspedu.try_;
/**
* @author wxb
* @version 1.0
* creat 2024-02-28-9:49
*/
public class TryCatchDetail {
public static void main(String[] args) {
//如果try代码块没有异常发生,则顺序执行try的代码块,不会进入到catch
try {
String str = "abc";
int a = Integer.parseInt(str);
System.out.println("数字" + a);
} catch (NumberFormatException e) {
System.out.println("异常信息 = " + e.getMessage());
} finally {
System.out.println("finally代码块被执行...");
}
}
}
输出结果为:
异常信息 = For input string: "abc"
finally代码块被执行...
4、可以有多个catch语句,捕获不同的异常(进行不同的业务处理),要求父类异常在后,子类异常在前,比如(Exception 在后,NullPointerException 在前),如果发生异常,只会匹配到一个catch。
package com.hspedu.try_;
/**
* @author wxb
* @version 1.0
* creat 2024-02-28-10:29
*/
public class TryCatchDetail02 {
public static void main(String[] args) {
//4、可以有多个catch语句,捕获不同的异常(进行不同的业务处理),要求父类异常在后,子类异常在前,
// 比如(Exception 在后,NullPointerException 在前),如果发生异常,只会匹配到一个catch。
try {
Person person = new Person();
person = null;
System.out.println(person.getName());
int num1 = 10;
int num2 = 0;
int res = num1 / num2;
} catch (NullPointerException e) {
System.out.println("空指针异常 = " + e.getMessage());
} catch (ArithmeticException e) {
System.out.println("算数异常 = " + e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Person {
private String name = "Mike";
public String getName() {
return name;
}
}
输出结果为:
空指针异常 = null
5、可以进行try-finally 配合使用,这种用法相当于没有捕获异常,因此程序会直接崩溃掉/退出。
应用场景,就是执行一段代码,不管是否发生异常,都必须执行某个业务逻辑。
基本语法:
try {
//可以发生异常的代码
} finally {
//总是要执行的代码
}
①程序没有异常
package com.hspedu.try_;
/**
* @author wxb
* @version 1.0
* creat 2024-02-28-10:50
*/
public class TryCatchDetail03 {
public static void main(String[] args) {
try {
int n1 = 10;
int n2 = 2;
System.out.println(n1 / n2);
} finally {
System.out.println("finally代码块被执行...");
}
System.out.println("程序继续执行...");
}
}
输出结果为:
5
finally代码块被执行...
程序继续执行...
②程序发生异常
package com.hspedu.try_;
/**
* @author wxb
* @version 1.0
* creat 2024-02-28-10:50
*/
public class TryCatchDetail03 {
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("程序继续执行...");//发生异常这行代码没有被执行
}
}
输出结果为:
finally代码块被执行...
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.hspedu.try_.TryCatchDetail03.main(TryCatchDetail03.java:13)
11.8、tryCatch练习(P451-452)
P451
1、
package com.hspedu.try_;
/**
* @author wxb
* @version 1.0
* creat 2024-02-28-16:36
*/
public class TryCatchExercise01 {
public static int method() {
try {
String[] names = new String[3];//1.三个字符串都为null
if (names[1].equals("tom")) {//2.所以这里会报出空指针异常
System.out.println(names[1]);
} else {
names[3] = "hspedu";
}
return 1;
} catch (ArrayIndexOutOfBoundsException e) {
return 2;
} catch (NullPointerException e) {//3.跳到这里
System.out.println("1");
return 3;//4.return会执行,但是并不会返回 3
} finally {//5.因为finally必须执行
return 4;//6.会返回4
}
}
public static void main(String[] args) {
System.out.println(method());
}
}
输出结果为:
1
4
2、
package com.hspedu.try_;
/**
* @author wxb
* @version 1.0
* creat 2024-02-28-16:48
*/
public class TryCatchExercise02 {
public static int method() {
int i = 1;
try {
i++;//1.i = 2
String[] names = new String[3];//2.三个字符串都为null
if (names[1].equals("tom")) {//3.所以这里会报出空指针异常
System.out.println(names[1]);
} else {
names[3] = "hspedu";
}
return 1;
} catch (ArrayIndexOutOfBoundsException e) {
return 2;
} catch (NullPointerException e) {//4.跳到这里
System.out.println("1");
return ++i;//5.会执行return ++i(i = 3),但是并不会返回
} finally {//6.因为finally必须执行
return ++i;//7.会返回++i(i = 4)
}
}
public static void main(String[] args) {
System.out.println(method());
}
}
输出结果为:
1
4
3、
package com.hspedu.try_;
/**
* @author wxb
* @version 1.0
* creat 2024-02-28-16:59
*/
public class TryCatchExercise03 {
public static int method() {
int i = 1;
try {
i++;//1.i = 2
String[] names = new String[3];//2.三个字符串都为null
if (names[1].equals("tom")) {//3.所以这里会报出空指针异常
System.out.println(names[1]);
} else {
names[3] = "hspedu";
}
return 1;
} catch (ArrayIndexOutOfBoundsException e) {
return 2;
} catch (NullPointerException e) {//4.跳到这里
System.out.println("1");
//5.会执行return ++i(i = 3) -----> 保存到临时变量 temp = 3,由于finally没有 return ,所以直接返回 3
return ++i;
} finally {//6.因为finally必须执行
++i;//7. i = 4
System.out.println("i = " + i);//输出 i = 4
}
}
public static void main(String[] args) {
System.out.println(method());//执行完method方法后,输出返回的 3
}
}
输出结果为:
1
i = 4
3
-
try-catch-finally执行顺序小结
1、如果没有出现异常,则执行try代码块中所有语句,不会执行catch代码块中的语句;如果有finally,最后还需要执行finally里面的语句
2、如果try代码块中发生异常,发生异常的语句的后面的代码不会再执行,将执行catch代码块中的语句。如果有finally,最后还需要执行finally里的语句。
P452
如果用户输入的不是一个整数,就提示它反复输入,知道输入一个整数为止
package com.hspedu.try_;
import java.util.Scanner;
/**
* @author wxb
* @version 1.0
* creat 2024-02-29-13:45
*/
public class TryCatchExercise04 {
//如果用户输入的不是一个整数,就提示它反复输入,知道输入一个整数为止
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num = 0;
String str = "";
while (true) {
System.out.print("请输入一个整数:");
str = scanner.next();
try {
num = Integer.parseInt(str);
break;
} catch (NumberFormatException e) {
System.out.println("输入错误,请重新输入\n");
}
}
System.out.println("num = " + num);
}
}
输出结果为:
请输入一个整数:abc
输入错误,请重新输入
请输入一个整数:123
num = 123
11.9、throws(P453~456)
11.9.1、throws入门案例(P453)
-
基本介绍
1、如果一个方法(中的语句执行时)可能发生某种异常,但是并不能确定如何处理这个异常,则此方法应显示地声明抛出异常,表面该方法将不对这些异常进行处理,而由该方法的调用者负责处理
2、在方法声明中用throws语句可以声明抛出异常的列表(可以抛出多个异常),throws后面的异常类型可以是方法中产生的异常类型,也可以是它的父类。
①
package com.hspedu.try_;
import java.io.FileInputStream;
/**
* @author wxb
* @version 1.0
* creat 2024-02-29-14:10
*/
public class Throws01 {
public static void main(String[] args) {
}
public void f2(){
FileInputStream fileInputStream = new FileInputStream("d://aa.txt");//报出异常
}
}
②添加throws FileNotFoundException,消除异常
package com.hspedu.try_;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
/**
* @author wxb
* @version 1.0
* creat 2024-02-29-14:10
*/
public class Throws01 {
public static void main(String[] args) {
}
public void f2() throws FileNotFoundException {
FileInputStream fileInputStream = new FileInputStream("d://aa.txt");
}
}
③
package com.hspedu.try_;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
/**
* @author wxb
* @version 1.0
* creat 2024-02-29-14:10
*/
public class Throws01 {
public static void main(String[] args) {
}
//使用throws抛出异常,让调用f2方法的调用者(即方法)处理
//throws后面的异常类型,可以是方法中产生的异常,也可以是方法中异常的父类
//throws后面可以是 异常列表,即可以抛出多个异常
public void f2() throws FileNotFoundException {
FileInputStream fileInputStream = new FileInputStream("d://aa.txt");
}
}
11.9.2、throws使用细节(P454)
-
注意事项和使用细节
1、对于编译异常,程序中必须处理,比如 try-catch 或者 throws
2、对于运行时的异常,程序中如果没有处理,默认就是throws的方式处理
package com.hspedu.try_;
/**
* @author wxb
* @version 1.0
* creat 2024-02-29-14:25
*/
public class ThrowsDetail {
//这里其实默认有 throws ArithmeticException,最终将异常抛给JVM机
public static void main(String[] args) throws ArithmeticException {
f2();
}
//这里其实默认有 throws ArithmeticException,将异常抛给调用f2方法的方法
public static void f2() throws ArithmeticException {
//1、对于编译异常,程序中必须处理,比如 try-catch 或者 throws
//2、对于运行时的异常,程序中如果没有处理,默认就是throws的方式处理
int n1 = 10;
int n2 = 0;
double res = n1 / n2;
}
}
输出结果为:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.hspedu.try_.ThrowsDetail.f2(ThrowsDetail.java:20)
at com.hspedu.try_.ThrowsDetail.main(ThrowsDetail.java:11)
3、子类重写父类的方法时,对抛出异常的规定:子类重写的方法,所抛出的异常类型要么和父类抛出的异常一致,要么为父类抛出的异常的类型和子类型
package com.hspedu.try_;
import java.io.FileInputStream;
/**
* @author wxb
* @version 1.0
* creat 2024-02-29-14:25
*/
public class ThrowsDetail {
//这里其实默认有 throws ArithmeticException,最终将异常抛给JVM机
public static void main(String[] args) throws ArithmeticException {
f2();
}
//这里其实默认有 throws ArithmeticException,将异常抛给调用f2方法的方法
public static void f2() throws ArithmeticException {
//1、对于编译异常,程序中必须处理,比如 try-catch 或者 throws
//2、对于运行时的异常,程序中如果没有处理,默认就是throws的方式处理
int n1 = 10;
int n2 = 0;
double res = n1 / n2;
}
}
//3、子类重写父类的方法时,对抛出异常的规定:子类重写的方法,
// 所抛出的异常类型要么和父类抛出的异常一致,要么为父类抛出的异常的类型和子类型
class Father {
public void ww() throws RuntimeException {
}
}
class Son extends Father {
@Override
public void ww() throws ArithmeticException {
}
}
4、在throws过程中,如果有方法 try-catch,就相当于处理异常,就可以不必使用throws
package com.hspedu.try_;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
/**
* @author wxb
* @version 1.0
* creat 2024-02-29-14:25
*/
public class ThrowsDetail {
//这里其实默认有 throws ArithmeticException,最终将异常抛给JVM机
public static void main(String[] args) throws ArithmeticException {
f2();
}
//这里其实默认有 throws ArithmeticException,将异常抛给调用f2方法的方法
public static void f2() throws ArithmeticException {
//1、对于编译异常,程序中必须处理,比如 try-catch 或者 throws
//2、对于运行时的异常,程序中如果没有处理,默认就是throws的方式处理
int n1 = 10;
int n2 = 0;
double res = n1 / n2;
}
public void f1() throws FileNotFoundException {// 1
//因为f3抛出的是编译异常,程序中必须处理,比如使用 try-catch 或者 throws
try {// 2
f3();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public void f3() throws FileNotFoundException {
FileInputStream fileInputStream = new FileInputStream("d://aa.txt");
}
public void f4() {
//f5抛出的是运行异常,在java中,运行异常不要求程序员显示处理,因为有默认处理机制(默认 抛到JVM机)
f5();
}
public void f5() throws ArithmeticException {
}
}
//3、子类重写父类的方法时,对抛出异常的规定:子类重写的方法,
// 所抛出的异常类型要么和父类抛出的异常一致,要么为父类抛出的异常的类型和子类型
class Father {
public void ww() throws RuntimeException {
}
}
class Son extends Father {
@Override
public void ww() throws ArithmeticException {
}
}
11.9.3、自定义异常(P455)
-
基本概念
当程序中出现了某些"错误",但该错误信息并没有在Throwable子类中描述处理,这个时候可以自己设计异常类,用于描述该错误信息。
-
自定义异常的步骤
1、定义类:自定义异常类名(程序员自己写)继承Exception或RuntimeException
2、如果继承Exception,属于编译异常
3、如果继承RuntimeException,属于运行异常(一般来说,继承RuntimeException,这样我们可以使用默认的处理机制)
-
自定义异常语法
class 自己定义的异常名 extends Exception或RuntimeException {
public 自己定义的异常名(String message) {//构造器
super(message);
}
}
-
自定义异常的应用实例
当我们接收Person对象年龄时,要求范围在18-120之间,否则抛出一个自定义异常(要求 继承RuntimeException),并给出提示信息
1、
package com.hspedu.try_;
/**
* @author wxb
* @version 1.0
* creat 2024-02-29-18:42
*/
public class CustomException {
public static void main(String[] args) {
int age = 80;
if (!(age > 18 && age < 90)) {
throw new AgeException("年龄范围错误...");
}
System.out.println("年龄为:" + age);
}
}
class AgeException extends RuntimeException {
public AgeException(String message) {//构造器
super(message);
}
}
输出结果为:
年龄为:80
2、
package com.hspedu.try_;
/**
* @author wxb
* @version 1.0
* creat 2024-02-29-18:42
*/
public class CustomException {
public static void main(String[] args) {
int age = 180;
if (!(age > 18 && age < 90)) {
throw new AgeException("年龄范围错误...");
}
System.out.println("年龄为:" + age);
}
}
class AgeException extends RuntimeException {
public AgeException(String message) {//构造器
super(message);
}
}
输出结果为:
Exception in thread "main" com.hspedu.try_.AgeException: 年龄范围错误...
at com.hspedu.try_.CustomException.main(CustomException.java:12)
11.9.4、throw和throws的区别(P456)
-
一览表
package com.hspedu.try_;
/**
* @author wxb
* @version 1.0
* creat 2024-02-29-19:03
*/
public class ThrowException {
public static void main(String[] args) {
try {
ReturnExceptionDemo.methodA();
} catch (Exception e) {
System.out.println(e.getMessage());
}
ReturnExceptionDemo.methodB();
}
}
class ReturnExceptionDemo {
static void methodA() {
try {
System.out.println("进入方法A");
throw new RuntimeException("制造异常");
} finally {
System.out.println("用A方法的finally");
}
}
static void methodB() {
try {
System.out.println("进入方法B");
} finally {
System.out.println("调用B方法的finally");
}
}
}
输出结果为:
进入方法A
用A方法的finally
制造异常
进入方法B
调用B方法的finally
11.10、异常课后作业(P457~458)
11.10.1、练习一(P457)
1、编程题
①编写应用程序EcmDef.java,接收命令行的两个参数(整数),计算两数相除
②计算两个数相除,要求使用方法 cal(int n1, int n2)
③对数据格式不正确、缺少命令行参数,除0进行异常处理
运行代码
①无异常
package com.hspedu.homework_;
/**
* @author wxb
* @version 1.0
* creat 2024-02-29-20:05
*/
public class Homework01 {
public static void main(String[] args) {
//①编写应用程序,接收命令行的两个参数(整数),计算两数相除
//②计算两个数相除,要求使用方法 cal(int n1, int n2)
//③对数据格式不正确、缺少命令行参数,除0进行异常处理
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);
System.out.println("两数相除结果为:" + res);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
} catch (ArithmeticException e) {
System.out.println("错误,被除数为0");
} catch (NumberFormatException e) {
System.out.println("存在字符");
}
}
public static double cal(int n1, int n2) {
return n1 / n2;
}
}
输出结果为:
两数相除结果为:2.0
②数据格式不正确
输出结果为:
存在字符
③缺少命令行参数
输出结果为:
参数个数不对
④除0进行异常处理
错误,被除数为0
11.10.2、练习二(P458)
2、说出以下代码是否会发生异常,如果会,是哪种异常?如果不会,则打印结果是什么?
package com.hspedu.homework_;
/**
* @author wxb
* @version 1.0
* creat 2024-03-01-9:17
*/
public class Homework02 {
public static void main(String[] args) {
if (args[4].equals("John")) {
System.out.println("AA");
} else {
System.out.println("BB");
}
Object o = args[2];
Integer i = (Integer) o;
}
}
①
package com.hspedu.homework_;
/**
* @author wxb
* @version 1.0
* creat 2024-03-01-9:17
*/
public class Homework02 {
public static void main(String[] args) {
//args没有传参,args.length = 0
//会报出ArrayIndexOutOfBoundsException异常
if (args[4].equals("John")) {//可能报出空指针异常
System.out.println("AA");
} else {
System.out.println("BB");
}
Object o = args[2];
Integer i = (Integer) o;
}
}
输出结果为:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at com.hspedu.homework_.Homework02.main(Homework02.java:12)
②传入参数
package com.hspedu.homework_;
/**
* @author wxb
* @version 1.0
* creat 2024-03-01-9:17
*/
public class Homework02 {
public static void main(String[] args) {
//args没有传参,args.length = 0
//会报出ArrayIndexOutOfBoundsException异常
if (args[4].equals("John")) {//可能报出空指针异常
System.out.println("AA");
} else {
System.out.println("BB");
}
Object o = args[2];
Integer i = (Integer) o;
}
}
输出结果为(还是空指针异常):
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at com.hspedu.homework_.Homework02.main(Homework02.java:12)
③传入五个参数
package com.hspedu.homework_;
/**
* @author wxb
* @version 1.0
* creat 2024-03-01-9:17
*/
public class Homework02 {
public static void main(String[] args) {
//args没有传参,args.length = 0
//会报出ArrayIndexOutOfBoundsException异常
if (args[4].equals("John")) {//可能报出空指针异常
System.out.println("AA");
} else {
System.out.println("BB");
}
Object o = args[2];//向上转型
Integer i = (Integer) o;//Integer不是Object的子类,进行不了向下转型,会报出ClassCastException类型转换异常
}
}
输出结果为:
BB
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
at com.hspedu.homework_.Homework02.main(Homework02.java:18)
3、写出下面代码运行结果
①
package com.hspedu.homework_;
/**
* @author wxb
* @version 1.0
* creat 2024-03-01-9:35
*/
public class Homework03 {
public static void main(String[] args) {
try {
func();
System.out.println("A");
} catch (Exception e) {
System.out.println("C");
}
System.out.println("D");
}
public static void func() {
try {
throw new RuntimeException();
} finally {
System.out.println("B");
}
}
}
输出结果为:
B
C
D
②
package com.hspedu.homework_;
/**
* @author wxb
* @version 1.0
* creat 2024-03-01-9:35
*/
public class Homework03 {
//B A D
public static void main(String[] args) {
try {
func();
System.out.println("A");
} catch (Exception e) {
System.out.println("C");
}
System.out.println("D");
}
public static void func() {
try {
throw new RuntimeException();
} catch (Exception e) {
System.out.println("解决了异常");
} finally {
System.out.println("B");
}
}
}
输出结果为:
解决了异常
B
A
D
4、写出程序结果
package com.hspedu.homework_;
/**
* @author wxb
* @version 1.0
* creat 2024-03-01-9:49
*/
public class Homework04 {
public static void main(String[] args) {
//BCD
try {
showException();
System.out.println("A");
} catch (Exception e) {
System.out.println("B");
} finally {
System.out.println("C");
}
System.out.println("D");
}
public static void showException() throws Exception {
throw new Exception();
}
}
输出结果为:
B
C
D