异常

package Error;

public class Test {
public static void main(String[] args) {
int i = 3 ;
try {
System.out.println(i/0);
//当不知道捕获的是什么类型的异常时,可以直接使用所有异常的父类
}catch (Exception e){ //Exception 所有异常的父类
//e.printStackTrace(); //获取当前的异常
System.out.println(e.getMessage()); //输出异常信息
}finally {
System.out.println(“最终执行的代码”);
}
System.out.println(“ok”);

}

}

package Error;

import New_Test.Employee;

public class Test1 {
public static void main(String[] args) {
//可以在main方法继续抛出异常
//man方法抛出异常直接抛到虚拟机上去了,就在程序中不能处理
// B b = new B();
// try {
// b.test();
// }catch (Exception e){
// e.printStackTrace();
// }

    C c = new C();
    try {
        c.test1(-10);
    } catch (MyException e) {
        e.printStackTrace();
    }

}

}
//class B {
// int i ;
// // 可以使用throws在代码这把出异常,在调用方去捕狭处理
// public void test () throws Exception { //抛出异常
// B b = null;
// System.out.println(b.i);
// }
//}
class C {
public void test1(int age) throws MyException{ //使用自定义异常
if (age > 0 && age < 150) {
System.out.println("年龄是: "+age);
}else
throw new MyException(“年龄不在0到150之间”);
}
}
class MyException extends Exception{ // 自定义异常类
public MyException (String msg){
super(msg);
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值