1.为什么使用throw、throws关键字
某个方法可能会产生异常,但不想在当前方法中处理,可以使用throw和throws抛出异常
2.区别
throws关键字:①声明方法可能抛出的异常,可以抛出多个异常,逗号分隔;②位置只能位于方法参数的括号后,不能用在代码块中;③抛出的是类名
throw关键字:①直接抛出一个异常实例,使用throw就一定会产生某种异常②用在代码块或方法体内;③抛出的是对象
3,为什么要使用自定义异常类
(1)JDK中定义的异常类无法准确描述特定异常信息
(2)由于java封装的特性,多数方法和属性不会直接暴露,查找异常代码的位置会非较为繁琐,通过throws/throw异常,可以直接从控制台上获取到异常的位置
如何使用自定义内部类示例如下
package com.bugOpe;
public class Test {
public static void main(String[] args) {
Student stu=new Student();
stu.setAge(10000);
System.out.println(stu.getAge());
}
}
class Student {
private int age;
public int getAge() {
return age;
}
public void setAge(int age) throws AgeException{
if(1<=age&&age<=150) {
this.age=age;
}else {
throw new AgeException("age范围:1~150!");
}
}
}
class AgeException extends RuntimeException{
AgeException (String message){ //定义构造方法
super(message); //使用super关键字调用父类构造方法
}
}
控制台输出如下
Exception in thread "main" com.bugOpe.AgeException: age范围:1~150!
at com.bugOpe.Student.setAge(Test.java:24)
at com.bugOpe.Test.main(Test.java:8)
//如果不使用super关键字,则调用父类无参构造方法,没有参数传入,则最终控制台不会输出throw关键字之后对象的参数内容,如下
Exception in thread "main" com.bugOpe.AgeException
at com.bugOpe.Student.setAge(Test.java:24)
at com.bugOpe.Test.main(Test.java:8)
需要说明的是
如果是运行时异常,自定义异常类需要直接或间接继承自RuntimeException
如果继承的是Exception,则为检查时异常,检查时异常需要显式处理,必须使用try-catch捕获或者抛出;
抛出的异常时运行时异常可以不使用throws,检查时异常必须显式使用throws;
throw语句不能连续出现,使用eclipse时会发现会提示不可达的错误,原因出现异常时会导致程序终止,类似于return
如果方法中的异常已经通过try-catch进行了捕获则无需再使用throws上抛该异常了,否则即使上抛也无效,只会做无用功。代码示例如下:
package com.bugOpe;
public class Test {
public static void show(int age) throws PrinteException{
if(age<0||age>150){
try {
throw new PrinteException("操作失败:年龄取值范围为0~150");
} catch (PrinteException e) {
System.out.println("show方法");
e.printStackTrace();
}
return;
}
System.out.println(age);
}
public static void main(String[] args) {
try {
show(1000);
} catch (PrinteException e) {
System.out.println("main方法");
e.printStackTrace();
}
}
}
class PrinteException extends RuntimeException{
PrinteException(String e){
super(e);
}
}
执行结果如下
show方法
com.bugOpe.PrinteException: 操作失败:年龄取值范围为0~150
at com.bugOpe.Test.show(Test.java:7)
at com.bugOpe.Test.main(Test.java:18)
/此处异常已经通过try-catch语句进行了处理,所以show方法无需再使用throws抛出异常了,否则即使上抛也无效:
执行代码会发现,即使这里异常被触发了,在main方法中catch依然没有执行,所以此时在通过throws抛出异常类纯属无用功/