







package top.exception.demo01;
public class Demo01 {
}
package top.exception.demo01;
public class Test {
public static void main(String[] args) {
int a =1;
int b =0;
//假设要捕获多个异常,从小到大!
try { //try监控区域
if (b==0){ // throw throws
throw new ArithmeticException();//主动抛出异常
}
System.out.println(a/b);
}catch (ArithmeticException e){ //catch(想要捕获的异常类型!) 捕获异常
System.out.println("程序出现异常,变量b不能为0");
}finally { //处理善后工作
System.out.println("finally");
}
// finally 可以不要finally, 假设IO,资源,关闭
}
public void a(){
b();
}
public void b(){
a();
}
}
package top.exception.demo01;
public class Test2 {
public static void main(String[] args) {
int a = 1;
int b = 0;
try { //快捷键 ctrl+Alt+t
System.out.println(a/b);
} catch (Exception e) {
System.exit(0);
e.printStackTrace(); //打印错误的栈信息
} finally {
}
}
}
package top.exception.demo02;
public class MyException extends Exception{
//传递数字> 10;
private int detail;
public MyException(int a) {
this.detail = a;
}
//toString
@Override
public String toString() {
return "MyException{" +
"detail=" + detail +
'}';
}
}
package top.exception.demo02;
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(1);
} catch (MyException e) {
//增加一些处理异常的代码
System.out.println("MyException=>" +e);
}
}
}
评论一下吧
取消回复