public class Test {
public static void main(String[] args) {
//可以在main方法上抛出异常,就直接抛到虚拟机上,就在程序中不能处理了
B b=new B();
try{//throws抛出的异常在这里捕获
b.test();
}
catch(Exception e){
e.getMessage();
e.printStackTrace();
}
}
}
class B{
int i ;
public void test() throws Exception{//可以使用throw在这抛出异常,在调用放捕获处理
B b=null;
System.out.println(b.i);
}
}
子类重写父类的方法时,不能抛出比父类方法更大范围的异常
class B{
int i ;
//NullpointerException的父类是Exception
public void test() throws NullPointerException{//可以使用throw在这抛出异常,在调用放捕获处理
B b=null;
System.out.println(b.i);
}
}
class C extends B{
@Override
//public void test() throws Exception 错误,子类重写父类的方法时,不能抛出比父类方法更大范围的异常 (Exception是NullpointerException的父类)
public void test() throws NullPointerException {
// TODO Auto-generated method stub
super.test();
}
}
人工抛出异常
class B{
int age;
public void test1(int age)throws Exception{
if(age>=0&&age<=150){
this.age=age;
System.out.println(this.age);
}else{
throw new Exception("年龄在0到150之间");
}
}
public static void main(String[] args) {
B b=new B();
try {
b.test1(-1);
} catch (Exception e) {
e.printStackTrace();
}
}
}
java.lang.Exception: 年龄在0到150之间
at day0226.B.test1(Test.java:46)
at day0226.Test.main(Test.java:24)
使用用户自定义异常类
java提供的异常的类一般是够用的,只有特殊的情况,可能需要自己编写异常类,这种情况很少见到,只要知道即可。
package day0226;
public class Test {
// public static void main(String[] args) {
// //可以在main方法上抛出异常,就直接抛到虚拟机上,就在程序中不能处理了
// B b=new B();
// try{//throws抛出的异常在这里捕获
// b.test();
// }
// catch(Exception e){
// e.getMessage();
// e.printStackTrace();
// }
//
//
// }
public static void main(String[] args) {
B b=new B();
try {
//b.test1(-1);
b.test2(-1);
} catch (Exception e) {
e.printStackTrace();
}
}
}
class B{
int i ;
//NullpointerException的父类是Exception
public void test() throws NullPointerException{//可以使用throw在这抛出异常,在调用放捕获处理
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(this.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(this.age);
}else{
throw new MyException("年龄在0到150之间");
}
}
}
class C extends B{
@Override
//public void test() throws Exception 错误,子类重写父类的方法时,不能抛出比父类方法更大范围的异常 (Exception是NullpointerException的父类)
public void test() throws NullPointerException {
// TODO Auto-generated method stub
super.test();
}
}
//使用用户自定义异常类
class MyException extends Exception{
public MyException (String message){
super(message);
}
}
day0226.MyException: 年龄在0到150之间
at day0226.B.test2(Test.java:56)
at day0226.Test.main(Test.java:25)