【大数据】学习笔记
文章目录
1 Java SE
第8章 异常
8.2 异常的处理
Java异常处理的五个关键字:try、catch、finally、throw、throws
8.2.1 捕获异常try…catch
【1】try…catch基本格式
捕获异常语法如下:
try{
可能发生xx异常的代码
}catch(异常类型1 e){
处理异常的代码1
}catch(异常类型2 e){
处理异常的代码2
}
....
try{}中编写可能发生xx异常的业务逻辑代码。
catch分支,分为两个部分,catch()中编写异常类型和异常参数名,{}中编写如果发生了这个异常,要做什么处理的代码。如果有多个catch分支,并且多个异常类型有父子类关系,必须保证小的子异常类型在上,大的父异常类型在下。
当某段代码可能发生异常,不管这个异常是编译时异常(受检异常)还是运行时异常(非受检异常),我们都可以使用try块将它括起来,并在try块下面编写catch分支尝试捕获对应的异常对象。
- 如果在程序运行时,try块中的代码没有发生异常,那么catch所有的分支都不执行。
- 如果在程序运行时,try块中的代码发生了异常,根据异常对象的类型,将从上到下选择第一个匹配的catch分支执行。此时try中发生异常的语句下面的代码将不执行,而整个try…catch之后的代码可以继续运行。
- 如果在程序运行时,try块中的代码发生了异常,但是所有catch分支都无法匹配(捕获)这个异常,那么JVM将会终止当前方法的执行,并把异常对象“抛”给调用者。如果调用者不处理,程序就挂了。
示例代码:
package com.dingjiaxiong.keyword;
/**
* @Projectname: BigDataStudy
* @Classname: TestTryCatch
* @Author: Ding Jiaxiong
* @Date:2023/4/27 14:58
*/
public class TestTryCatch {
public static void main(String[] args) {
try {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int result = a / b;
System.out.println("result = " + result);
} catch (NumberFormatException e) {
System.out.println("数字格式不正确,请输入两个整数");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数字个数不正确,请输入两个整数");
} catch (ArithmeticException e) {
System.out.println("第二个整数不能为0");
}
System.out.println("你输入了" + args.length + "个参数。");
System.out.println("你输入的被除数和除数分别是:");
for (int i = 0; i < args.length; i++) {
System.out.print(args[i] + " ");
}
System.out.println();
}
}
运行结果
【2】JDK1.7try…catch新特性
如果多个catch分支的异常处理代码一致,那么在JDK1.7之后还支持如下写法:
try{
可能发生xx异常的代码
}catch(异常类型1 | 异常类型2 e){
处理异常的代码1
}catch(异常类型3 e){
处理异常的代码2
}
....
示例代码:
package com.dingjiaxiong.keyword;
/**
* @Projectname: BigDataStudy
* @Classname: TestJDK7
* @Author: Ding Jiaxiong
* @Date:2023/4/27 15:06
*/
public class TestJDK7 {
public static void main(String[] args) {
try {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int result = a / b;
System.out.println("result = " + result);
} catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
System.out.println("数字格式不正确,请输入两个整数");
} catch (ArithmeticException e) {
System.out.println("第二个整数不能为0");
}
System.out.println("你输入了" + args.length + "个参数。");
System.out.println("你输入的被除数和除数分别是:");
for (int i = 0; i < args.length; i++) {
System.out.print(args[i] + " ");
}
System.out.println();
}
}
【3】在catch分支中获取异常信息
如何获取异常信息,Throwable类中定义了一些查看方法:
-
public String getMessage()
:获取异常的描述信息,原因(提示给用户的时候,就提示错误原因。 -
public void printStackTrace()
:打印异常的跟踪栈信息并输出到控制台。
包含了异常的类型,异常的原因,还包括异常出现的位置,在开发和调试阶段,都得使用printStackTrace。
8.2.2 finally块
【1】finally块
因为异常会引发程序跳转,从而会导致有些语句执行不到。而程序中有一些特定的代码无论异常是否发生,都需要执行。例如,IO流的关闭,数据库连接的断开等。这样的代码通常就会放到finally块中。
try{
}catch(...){
}finally{
无论try中是否发生异常,也无论catch是否捕获异常,也不管try和catch中是否有return语句,都一定会执行
}
或
try{
}finally{
无论try中是否发生异常,也不管try中是否有return语句,都一定会执行。
}
注意:finally不能单独使用。
当只有在try或者catch中调用退出JVM的相关方法,例如System.exit(0),此时finally才不会执行,否则finally永远会执行。
示例代码:
package com.dingjiaxiong.keyword;
import java.util.InputMismatchException;
import java.util.Scanner;
/**
* @Projectname: BigDataStudy
* @Classname: TestFinally
* @Author: Ding Jiaxiong
* @Date:2023/4/27 15:08
*/
public class TestFinally {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
try {
System.out.print("请输入第一个整数:");
int a = input.nextInt();
System.out.print("请输入第二个整数:");
int b = input.nextInt();
int result = a / b;
System.out.println(a + "/" + b + "=" + result);
} catch (InputMismatchException e) {
System.out.println("数字格式不正确,请输入两个整数");
} catch (ArithmeticException e) {
System.out.println("第二个整数不能为0");
} finally {
System.out.println("程序结束,释放资源");
input.close();
}
}
}
【2】finally与return
形式一:从try回来
package com.dingjiaxiong.keyword;
/**
* @Projectname: BigDataStudy
* @Classname: TestReturn
* @Author: Ding Jiaxiong
* @Date:2023/4/27 15:09
*/
public class TestReturn {
public static void main(String[] args) {
int result = test("12");
System.out.println(result);
}
public static int test(String str) {
try {
Integer.parseInt(str);
return 1;
} catch (NumberFormatException e) {
return -1;
} finally {
System.out.println("test结束");
}
}
}
形式二:从catch回来
package com.dingjiaxiong.keyword;
/**
* @Projectname: BigDataStudy
* @Classname: TestReturn
* @Author: Ding Jiaxiong
* @Date:2023/4/27 15:09
*/
public class TestReturn {
public static void main(String[] args) {
int result = test("a");
System.out.println(result);
}
public static int test(String str) {
try {
Integer.parseInt(str);
return 1;
} catch (NumberFormatException e) {
return -1;
} finally {
System.out.println("test结束");
}
}
}
形式三:从finally回来
package com.dingjiaxiong.keyword;
/**
* @Projectname: BigDataStudy
* @Classname: TestReturn
* @Author: Ding Jiaxiong
* @Date:2023/4/27 15:09
*/
public class TestReturn {
public static void main(String[] args) {
int result = test("a");
System.out.println(result);
}
public static int test(String str) {
try {
Integer.parseInt(str);
return 1;
} catch (NumberFormatException e) {
return -1;
} finally {
System.out.println("test结束");
return 0;
}
}
}
8.2.3 转换异常处理位置throws
【1】throws 编译时异常
如果在编写方法体的代码时,某句代码可能发生某个编译时异常,不处理编译不通过,但是在当前方法体中可能不适合处理或无法给出合理的处理方式,就可以通过throws在方法签名中声明该方法可能会发生xx异常,需要调用者处理。
声明异常格式:
修饰符 返回值类型 方法名(参数) throws 异常类名1,异常类名2…{ }
在throws后面可以写多个异常类型,用逗号隔开。
代码演示:
package com.dingjiaxiong.keyword;
/**
* @Projectname: BigDataStudy
* @Classname: TestThrowsCheckedException
* @Author: Ding Jiaxiong
* @Date:2023/4/27 15:12
*/
public class TestThrowsCheckedException {
public static void main(String[] args) {
System.out.println("上课.....");
try {
afterClass();//换到这里处理异常
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("准备提前上课");
}
System.out.println("上课.....");
}
public static void afterClass() throws InterruptedException {
for (int i = 10; i >= 1; i--) {
Thread.sleep(1000);//本来应该在这里处理异常
System.out.println("距离上课还有:" + i + "分钟");
}
}
}
【2】throws 运行时异常
当然,throws后面也可以写运行时异常类型,只是运行时异常类型,写或不写对于编译器和程序执行来说都没有任何区别。如果写了,唯一的区别就是调用者调用该方法后,使用try…catch结构时,IDEA可以获得更多的信息,需要添加什么catch分支。
package com.dingjiaxiong.keyword;
import java.util.InputMismatchException;
import java.util.Scanner;
/**
* @Projectname: BigDataStudy
* @Classname: TestThrowsRuntimeException
* @Author: Ding Jiaxiong
* @Date:2023/4/27 15:13
*/
public class TestThrowsRuntimeException {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
try {
System.out.print("请输入第一个整数:");
int a = input.nextInt();
System.out.print("请输入第二个整数:");
int b = input.nextInt();
int result = divide(a, b);
System.out.println(a + "/" + b + "=" + result);
} catch (ArithmeticException | InputMismatchException e) {
e.printStackTrace();
} finally {
input.close();
}
}
public static int divide(int a, int b) throws ArithmeticException {
return a / b;
}
}
【3】方法重写对于throws要求
方法重写时,对于方法签名是有严格要求的:
(1)方法名必须相同
(2)形参列表必须相同
(3)返回值类型
- 基本数据类型和void:必须相同
- 引用数据类型:<=
(4)权限修饰符:>=,而且要求父类被重写方法在子类中是可见的
(5)不能是static,final修饰的方法
(6)throws异常列表要求
- 如果父类被重写方法的方法签名后面没有 “throws 编译时异常类型”,那么重写方法时,方法签名后面也不能出现“throws 编译时异常类型”。
- 如果父类被重写方法的方法签名后面有 “throws 编译时异常类型”,那么重写方法时,throws的编译时异常类型必须<=被重写方法throws的编译时异常类型。
- 方法重写,对于“throws 运行时异常类型”没有要求。
package com.dingjiaxiong.keyword;
import java.io.IOException;
/**
* @Projectname: BigDataStudy
* @Classname: TestOverride
* @Author: Ding Jiaxiong
* @Date:2023/4/27 15:14
*/
public class TestOverride {
}
class Father {
public void method() throws Exception {
System.out.println("Father.method");
}
}
class Son extends Father {
@Override
public void method() throws IOException, ClassCastException {
System.out.println("Son.method");
}
}
8.2.4 异常throw
Java程序的执行过程中如出现异常,会生成一个异常类对象,该异常对象将被提交给Java运行时系统,这个过程称为抛出(throw)异常。异常对象的生成有两种方式:
- 由虚拟机自动生成:程序运行过程中,虚拟机检测到程序发生了问题,就会在后台自动创建一个对应异常类的实例对象并抛出——自动抛出。
- 由开发人员手动创建:new 异常类型(【实参列表】);,如果创建好的异常对象不抛出对程序没有任何影响,和创建一个普通对象一样,但是一旦throw抛出,就会对程序运行产生影响了。
使用格式:
throw new 异常类名(参数);
throw语句抛出的异常对象,和JVM自动创建和抛出的异常对象一样。
- 如果是编译时异常类型的对象,同样需要使用throws或者try…catch处理,否则编译不通过。
- 如果是运行时异常类型的对象,编译器不提示。
- 但是无论是编译时异常类型的对象,还是运行时异常类型的对象,如果没有被try…catch合理的处理,都会导致程序崩溃。
throw语句会导致程序执行流程被改变,throw语句是明确抛出一个异常对象,因此它下面的代码将不会执行,如果当前方法没有try…catch处理这个异常对象,throw语句就会代替return语句提前终止当前方法的执行,并返回一个异常对象给调用者。
package com.dingjiaxiong.keyword;
/**
* @Projectname: BigDataStudy
* @Classname: TestThrow
* @Author: Ding Jiaxiong
* @Date:2023/4/27 15:15
*/
public class TestThrow {
public static void main(String[] args) {
try {
System.out.println(max());
} catch (Exception e) {
e.printStackTrace();
}
try {
System.out.println(max(4));
} catch (Exception e) {
e.printStackTrace();
}
try {
System.out.println(max(4, 2, 31, 1));
} catch (Exception e) {
e.printStackTrace();
}
}
public static int max(int... nums) {
if (nums == null || nums.length == 0) {
throw new IllegalArgumentException("没有传入任何整数,无法获取最大值");
}
int max = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] > max) {
max = nums[i];
}
}
return max;
}
}