异常处理
-
抛出异常
-
捕获异常
异常处理五个关键字
-
try、catch、finally、throw、throws
try catch finally
package oop.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 c){//捕获异常,如果异常则执行
System.out.println("程序出现异常");
}finally {//出不出异常都会执行
System.out.println("finally");
}
}
}
finally可以不要,假设IO、资源需要关闭,关闭操作可以放在finally里
捕获Error:
package oop.Exception;
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
try {//try监控区域是否有异常
new Test().a();
}catch (Throwable c){//捕获异常,如果异常则执行,throwable级别最高,能捕获所有异常
System.out.println("程序出现异常");
}finally {//出不出异常都会执行
System.out.println("finally");
}
}
public void a(){
b();
}
public void b(){
a();
}
}
可以有多个catch,但捕获级别要从小到大
package oop.Exception;
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
try {//try监控区域是否有异常
new Test().a();
}catch (Error c) {//捕获异常,如果异常则执行
System.out.println("Error");
}
catch (Exception d){
System.out.println("Exception");
}
catch (Throwable e){
System.out.println("Throwable");
}
finally {//出不出异常都会执行
System.out.println("finally");
}
}
public void a(){
b();
}
public void b(){
a();
}
}
package oop.Exception;
public class Test {
public static void main(String[] args) {
try {
new Test().a(1,0);
} catch (ArithmeticException e) {
e.printStackTrace();
}
}
//假设这个方法中处理不聊这个异常。方法上抛出异常
public void a(int x,int y) throws ArithmeticException{
if(y==0){//主动抛出异常 throw throws
throw new ArithmeticException();//一般在方法中使用
}
System.out.println(x/y);
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了