//抛出异常
public class Test5 {
public static void main(String[] args) throws Exception {//可以在main方法中继续抛出异常
//main方法抛出异常直接抛到虚拟机上去了,就在程序中不能处理了
B b = new B();
try {
b.test();
}catch(Exception e) {
e.printStackTrace();
}
b.test(); // 抛出空指针异常
b.test1(-100); //人工抛出异常
b.test2(-100);
try {
b.test2(-100);
}catch(Exception e) {
System.out.println(e.getMessage());
}
}
}
class B {
int i;
//NullPointerException的父类是Exception
public void test() throws NullPointerException { //可以使用throws在代码这里抛出异常,在调用方捕获处理
B b = null;
System.out.println(b.i);
}
int age;
public void test1(int age) throws Exception { //人工抛出异常
if(age>=0&&age<=150) {
this.age=age;
System.out.println("年龄是:"+age);
}else {
throw new Exception("年龄在0到150之间");
}
}
public void test2(int age) throws MyException {
if(age>=0&&age<=150) {
this.age=age;
System.out.println("年龄是:"+age);
}else {
throw new MyException("年龄在0到150之间");
}
}
}
//子类重写父类的方法时,子类不能抛出比父类方法更大范围的异常,所以这里不能用Exception
class C extends B{
@Override
public void test() throws NullPointerException {
// TODO Auto-generated method stub
super.test();
}
}
// 用户自定义异常类
// java提供异常的类,一般是够用的,只有特殊的情况可能需要自己编写异常的类,这种情况很少见
class MyException extends Exception{
public MyException (String msg) {
super(msg);
}
}
java抛出异常
最新推荐文章于 2024-05-12 19:03:32 发布