抛出异常与自定义异常
1.Markdown语法学习2.HelloWorld3.next 与 nextline 方法使用介绍4.运算符5.变量6.课程问题7.Array类8.方法的创建与使用9.打印正三角形10.For的基础结构11.While 的基础结构12.Switch的基础结构13.If的三种基础结构14.求和与平均数
15.抛出异常与自定义异常
16.内部类17.接口18.抽象类19.Static关键字20.instanceof 和 类型转换21.多态22.方法的重载23.Super的基本使用24.封装的基本使用25.构造器26.方法的回顾27.数组的简单操作28.二维数组的创建和遍历29.冒泡排序30.数组的定义和初始化抛出异常
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
try {
new Test().test(1,0);
} catch (ArithmeticException e) {
throw new RuntimeException(e);
} finally {
}
}
// 假设者方法中,处理不了这个异常,throws 方法 !上! 抛出异常 ,
public void test(int a,int b) throws ArithmeticException{
if (b==0){
throw new ArithmeticException();//主动抛出异常 throw一般在方法 !中!使用
}
}
}
/*
//如果要捕获多个异常:catch()需要从小到大书写
try {//try 监控区域
System.out.println(a/b);
}catch (Error e){//catch 捕获区域
System.out.println("Error");
}catch (Exception e){
System.out.println("Exception");
}catch (Throwable e){
System.out.println("Throwable");
}
finally {// 无论是否出现异常,都会执行finally,处理善后工作
//可以不使用 finally , 一般在IO流中,对一些资源进行释放、关闭
System.out.println("finally");
}
*/
public class Test02 {
public static void main(String[] args) {
int a = 1;
int b = 0;
// 快捷键 Ctrl + Alt + T
try {
System.out.println(a/b);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
}
}
}
自定义异常
// 自定义的异常类
public class MyException extends Exception{
// 传递数字 大于10 抛出异常
private int detial;
public MyException(int detial) {
this.detial = detial;
}
//toString:异常打印的消息
@Override
public String toString() {
return "MyException{" +
"detial=" + detial +
'}';
}
}
public class Test03 {
// 可能会存在异常的方法
static void test(int a) throws MyException {
System.out.println("传递的参数为:" + a);
if(a>10){
throw new MyException(a);
}else {
System.out.println("OK");
}
}
public static void main(String[] args) {
try {
test(11);
} catch (MyException e) {
System.out.println("MyException" + e);
}
}
}
处理运行时异常时,采用逻辑去合理规避同时辅助 try-catch 处理
在多重catch块后面,可以加一个catch(Exception)来处理可能会被遗漏的异常
对于不确定的代码,也可以加上 try-catch,处理潜在的异常
尽量去处理异常,切忌只是简单地调用 printStackTrace()去打印输出
具体如何处理异常,要根据不同的业务需求和异常类型去决定
尽量添加finally语句块去释放占用的资源
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异