目录
throw与throws同为处理异常的方法。如果只是单纯的输出提示,无法定位到程序的哪个地方出现了问题,这是则需要使用throw/throws处理异常,来告诉编码者代码错误的位置。例:
public class Student {
private int age;
public void setAge(int age) {//封装
if(age<0 || age>120) {
//System.out.println("年龄范围:大于0岁,小于120岁");
//单纯的输出提示无法定位到程序的哪个地方出现了问题 :利用 throw 异常处理
throw new NullPointerException("年龄范围:大于0岁,小于120岁");//能够定位错误的地方
一、throw与throws的关系
如果throw抛出的是由运行时异常创建的对象,则不需要显示使用throws;否则需要显示使用throws,或try-catch-finally用来将异常处理;
注:(1)当使用throws时,运行时异常仍然只是被抛出,所以依旧可以执行下面的代码
public static void div(int a,int b)throws Exception{//用来将错误抛出,main方法里之后的代码继续执行
if(b==0) {
throw new Exception("分母不为0");
}else{
System.out.println(a/b);
}
}
public static void main(String[] args) {
try {
div(1,0);
}catch(Exception e) {
System.out.println("问题被抛出,没解决就执行");
}
}
(2)当使用 try-catch-finally时,运行时异常将被解决,下面的代码将不会被执行
public static void div(int a,int b){//用try-catch解决了,mian方法里之后的代码不再进行
if(b==0) {
try {
throw new Exception("分母不为0");
}catch (Exception e) {
e.printStackTrace();//异常已解决
}
}else {
System.out.println(a/b);
}
public static void main(String[] args) {
try {
div(1,0);
}catch(Exception e) {
System.out.println("问题被抛出,没解决就执行");//不会被执行
}
}
二、throw与throws的区别
(1)抛出的对象不同
throw:抛出异常类创建的对象
throws:抛出异常类
(2)使用的位置不同
throw:方法内或代码块内
throws:方法参数列表括号的后面
throw:
try {
throw new AgeException("年龄范围:大于0岁,小于120岁");
}catch(AgeException e) {
e.printStackTrace();
}
public static void div(int a,int b)throws Exception{
}