当前位置: 首页 > news >正文

Java SE(12)——异常(Exception)

1.概念

在Java中,异常(Exception)是指程序在运行过程中发生的不正常情况
例如:

  • 算数异常(ArithmeticException) 在这里插入图片描述
  • 空指针异常(NullPointerException) 在这里插入图片描述
  • 数组越界异常(ArrayIndexOutOfBoundsException) 在这里插入图片描述

根据上述的异常信息可以看出:每个具体的异常都有一个类来进行描述

2.异常的体系

在这里插入图片描述

Throwable:是所有错误(Error)和异常(Exception)的父类。它有两个主要的子类:ErrorException

Error:Error及其子类表示Java虚拟机(JVM)无法处理的严重问题。这些错误通常是不可恢复的,应用程序不应该尝试去捕捉这些错误

Exception:Exception及其子类表示应用程序可以捕获和处理的问题。Exception又可以分为两大类:

  • 1.检查型异常(Checked Exception)
  • 2.非检查型异常(Unchecked Exception)

3.错误(Error)

下面是栈溢出错误代码示例:

public class Demo {public void demo() {demo();}public static void main(String[] args) {Demo demo = new Demo();demo.demo();}
}

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

在Java中,每次调用方法都会在虚拟机栈上为该方法开辟一个方法栈帧。上述代码中无限递归调用demo()方法就会无限地开辟方法栈帧。因为栈空间是有限的,所以就会抛出StackOverflowError错误。像这种错误一旦发生整个应用程序就会立刻崩溃,唯一的解决办法就是从根源上修改代码

4.异常(Exception)

4.1 检查型异常(Checked Exception)

检查型异常在编译阶段就会被检查,编译器强制要求程序员处理这些异常,比如:CloneNotSupportedException,IOException等。如果程序中抛出了这些异常,必须使用throws进行声明或者使用try-catch进行处理在这里插入图片描述

4.2 非检查型异常(Unchecked Exception)

非检查型异常在编译阶段不会被检查,是在运行时可能发生的异常,比如:ArithmeticException,NullPointerException,ArrayIndexOutOfBoundsException等。这些异常如果程序员不做处理,就会交给JVM进行处理在这里插入图片描述

5.异常的处理

5.1 throw

throw关键字用来显式抛出一个异常

public class Demo {public static int function(int num){if(num == 0){throw new ArithmeticException();}return 10 / num;}public static void main(String[] args){System.out.println(function(0));}
}

5.2 throws

throws关键字用于方法签名中,声明该方法可能抛出的异常。它主要用于处理检查型异常(Checked
Exceptions),即那些在编译时需要被处理的异常。通过使用throws,方法可以声明它不处理某些异常,而是将异常的处理责任传递给调用该方法的代码

在这里插入图片描述

5.3 try-catch

try-catch允许程序员捕捉并处理应用程序允许过程中可能出现的异常,从而防止程序因未处理的异常而中断

当程序中抛出非检查型异常时,如果程序员不介入解决,就会交由JVM来处理。当JVM处理异常时会中断当前应用程序

public class Demo {public static void function(int num){if(num == 0){throw new ArithmeticException();}System.out.println("程序继续执行");}public static void main(String[] args){function(0);}
}

运行结果:
在这里插入图片描述
使用try-catch处理该异常:

public class Demo {public static void function(int num){if(num == 0){throw new ArithmeticException();}}public static void main(String[] args){try {function(0);}catch (ArithmeticException e){System.out.println("成功捕捉到该异常并处理");}System.out.println("程序继续执行");}
}

运行结果:
在这里插入图片描述

注意:

  • 1.try块内抛出异常后的代码将不会被执行 在这里插入图片描述
  • 2.如果抛出异常类型与catch时异常类型不匹配,即异常不会被成功捕获,也就不会被处理,继续往外抛,直到JVM收到后中断程序——异常是按照类型来捕获在这里插入图片描述
  • 3 try中可能会抛出多个不同的异常对象,则必须用多个catch来捕获——即多种异常,多次捕获在这里插入图片描述
  • 4.如果异常之间具有父子关系,一定是子类异常在前catch父类异常在后catch,否则语法错误 在这里插入图片描述
  • 5.可以使用Exception来一次性捕获所有异常,实现一劳永逸(一般不推荐,不利于排查问题)

5.4 finally

finally是Java中异常处理机制的一部分,通常与try-catch块一起使用。无论try块中的代码是否抛出异常,finally块中的代码都会执行。在finally块中主要执行清理操作,如释放资源、关闭文件或数据库连接等
在这里插入图片描述

6.自定义异常

虽然Java中已经内置了非常多的异常类,但不一定完全符合用户的需求,所以用户也可以自定义自己期望的异常

6.1 定义方式

如果希望自定义非检查型异常,可以继承自RuntimeException及其子类

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

如果希望自定义检查型异常,可以继承自IOException等检查型异常

public class PasswordErrorException extends IOException {public PasswordErrorException() {super();}public PasswordErrorException(String message) {super(message);}
}

6.2 使用自定义异常来实现登录功能

public class PasswordErrorException extends RuntimeException {public PasswordErrorException() {super();}public PasswordErrorException(String message) {super(message);}
}
public class UsernameErrorException extends RuntimeException{public UsernameErrorException(String message){super(message);}public UsernameErrorException(){super();}
}
public class Login {public void login(String username, String password){if(!"admin".equals(username) ){throw new UsernameErrorException("用户名错误");}if(!"123456".equals(password)){throw new PasswordErrorException("密码错误");}System.out.println("登录成功");}public static void main(String[] args) {Login login = new Login();try {login.login("admin", "123456");}catch (UsernameErrorException | PasswordErrorException e){//printStackTrace()方法可以打印出抛异常的具体位置e.printStackTrace();}System.out.println("程序继续执行");}
}

相关文章:

  • InternVL3: 利用AI处理文本、图像、视频、OCR和数据分析
  • C++11异步编程 --- async
  • SQL易混点:你知道ON 和 WHERE 的区别吗
  • 软考 系统架构设计师系列知识点之杂项集萃(58)
  • JIT+Opcache如何配置才能达到性能最优
  • Spring Boot 整合 Redis 实战
  • S7-1200 PLC与梅特勒-托利多IND360称重仪表通信
  • python酒店健身俱乐部管理系统
  • 遨游5G-A防爆手机:赋能工业通信更快、更安全
  • 【Ansible】基于windows主机,采用NTLM+HTTPS 认证部署
  • Flutter小白入门指南
  • USB3.0拓展坞制作学习
  • 芯片:金线的作用
  • RDD案例数据清洗
  • Maven 动态插件配置:Profile的灵活集成实践
  • PowerShell 实现 conda 懒加载
  • 新建一个reactnative 0.72.0的项目
  • 【神经网络与深度学习】局部最小值和全局最小值
  • Python中元组(Tuple)使用详解和注意事项
  • 微服务的“导航系统”:使用Spring Cloud Eureka实现服务注册与发现
  • 硅料收储挺价“小作文”发酵光伏板块罕见大涨,知情人士:确实在谈
  • 75万买299元路由器后续:重庆市纪委、财政局、教委联合调查
  • 北京“准80后”干部兰天跨省份调任新疆生态环境厅副厅长
  • 甩掉“肥胖刺客”,科学减重指南来了
  • “不为一时一事所惑,不为风高浪急所扰”——习近平主席对俄罗斯进行国事访问并出席纪念苏联伟大卫国战争胜利80周年庆典纪实
  • 种罂粟喂鸡防病?四川广元一村民非法种植毒品原植物被罚​