Java异常01——捕获和抛出异常
2024-10-17 15:47:22
捕获和抛出异常
异常处理五个关键字
try , catch , finally , throw , throws
try catch finally(快捷键:选中要要监控的代码语句 快捷键: ctrl + alt + t)
package exception;
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
try{//try 监控区域
System.out.println(a/b);
}catch (ArithmeticException e){//catch 捕获异常
System.out.println("程序出现异常,b不能为0");
}finally {// 处理善后工作
System.out.println("finally");
}
//finally 可以不要finally, 用: 假设IO,资源需要关闭
}
}
---------------------------------------------------------------------------------------------------
// 选中要要监控的代码语句 快捷键: ctrl + alt + t
package exception;
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
// 假设要捕获多个异常: 异常类型:从小到大
try{//try 监控区域
System.out.println(a/b);
}catch (Error e){//catch(想要捕获的异常类型!) 捕获异常
System.out.println("Error");
}catch (Exception e){
System.out.println("Exception");
}catch (Throwable t){
System.out.println("Throwable");
}
finally {// 处理善后工作
System.out.println("finally");
}
//finally 可以不要finally, 用: 假设IO,资源需要关闭
}
}
throw throws
package exception;
public class Test {
public static void main(String[] args) {
new Test().test(1,0);
}
public void test(int a , int b){
if(b==0){// throw throws
throw new ArithmeticException();//主动抛出异常,一般在方法中使用 throw
}
System.out.println(a/b);
}
}
---------------------
package exception;
public class Test {
public static void main(String[] args) {
try {
new Test().test(1,0); // try catch
} catch (ArithmeticException e) {
e.printStackTrace();
}
}
// 假设这个方法中,处理不了这个异常。方法上抛出异常
public void test(int a , int b) throws ArithmeticException{ // throws
if(b==0){// throw throws
throw new ArithmeticException();//主动抛出异常,一般在方法中使用
}
System.out.println(a/b);
}
}
学习内容源自视频:b站狂神说Java
最新文章
- ubuntu笔记
- Trace和Debug主要用法
- CentOS7 安装kubernetes
- maven 项目出现 java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
- 用JAVA写一个冒泡排序
- laravel整理笔记(一)
- [Day24]IO(转换流、缓冲流)
- (译)MySQL 8.0实验室---MySQL中的倒序索引(Descending Indexes)
- BABOK概述
- use . adb . get wifi
- Android开发 - 获取系统输入法高度的正确姿势
- Ubuntu 14.04 vi 退格键不能删除字符
- 缺少dll文件的解决方法
- (回溯法)数组中和为S的N个数
- 【转】Linux(BASH)命令搜索机制
- Flink学习笔记:Connectors之kafka
- adminlte+layui框架搭建1
- hadoop-2.0.0-cdh4.6.0、sqoop-1.4.3-cdh4.6.0、mahout-0.7-cdh4.6.0 安装笔记
- Git使用之Permission Denied问题解决
- Java实现求二叉树的路径和