Day16-异常
异常机制
一.Error和Exception
1.什么是异常
2.异常体系结构
3.Error和Exception
Error
Exception
二.捕获和抛出异常
1.异常处理机制
抛出异常
捕获异常
异常处理五个关键字:
try,catch.finally,throw,throws
例1:捕获Exception
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,资源,关闭
}
}
例2:捕获Error
package exception;
public class Test {
public static void main(String[] args) {
int a=1;
int b=0;
try {//try监控区域
new Test().a();
}catch (Error e){//这里用Throwable也可以//catch(想要捕获的异常类型)捕获异常
System.out.println("成功捕获Error");
}finally {//处理善后工作
System.out.println("finally");
}
//finally 可以不要finally。假设IO,资源,关闭
}
public void a(){
b();
}
public void b(){
a();
}
}
例3:假设捕获多个异常
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){//这里用Throwable也可以//catch(想要捕获的异常类型)捕获异常
System.out.println("成功捕获Error");
}catch (Exception e){
System.out.println("成功捕获Exception");
}catch (Throwable e){
System.out.println("成功捕获Throwable");
} finally {//处理善后工作
System.out.println("finally");
}
//finally 可以不要finally。假设IO,资源,关闭
}
public void a(){
b();
}
public void b(){
a();
}
}
例4:主动抛出异常
package exception;
public class test2 {
public static void main(String[] args) {
try {
new test2().test(1,0);
} catch (ArithmeticException e) {
e.printStackTrace();
}
}
//假设这方法中,吃力不了这个异常,方法上抛出异常
public void test(int a,int b)throws ArithmeticException{
if (b == 0) {// throw throws
throw new ArithmeticException();//主动抛出异常,一般在方法中使用
}
}
}
三.自定义异常
1.自定义异常类
package MyException;
//自定义的异常类
public class myexception extends Exception{
//传递数字>10
private int detail;
public myexception(int a) {
this.detail = a;
}
//to string:异常的打印信息
@Override
public String toString() {
return "myexception{" + "detail=" + detail + '}';
}
}
2.测试类
package MyException;
public class test {
//可能会存在异常的方法
static void test(int a) throws myexception {
System.out.println("传递的参数为:"+a);
if (a>10){
throw new myexception(a);//抛出
}
System.out.println("OK");
}
public static void main(String[] args) {
try {
test(11);
} catch (MyException.myexception e) {
System.out.println("my exception-->"+e);
}
}
}
//运行结果
//传递的参数为:11
//my exception-->myexception{detail=11}
实际应用中的经验总结
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术