抛出异常throw或throws

抛出异常

因为异常类型不同,抛出异常的方法也不同,具体分为:

  1. 系统自动抛出的异常
  2. 指定方法抛出的异常

系统定义的所有运行时异常(可看上编文章)都可以由系统自动抛出。而指定方法抛出的异常就需要用关键字throw、throws来抛出了。

如一个方法可能存在异常,但不能确定如何处理,则此方法就该抛出异常,由该方法的调用者进行处理。这样该方法就不用写try-catch-finally语句来处理。

语法格式:

在方法体内是有throw语句抛出异常:

throw 由异常类所产生的对象
在方法头部添加throws语句来抛出异常:(多异常类型用,隔开)

[修饰符] 返回值类型 方法名 ([参数列表]throws 异常类列表

当一个方法抛出异常后该方法内没有异常处理语句,系统就会将异常向上传递,由调用该方法的程序来处理异常。以此类推一层层往上追溯,一直到main方法为止。是必须由异常处理程序的,否则会报错。

  1. 使用throw语句在方法内抛出异常,并在方法内进行相应的处理:
public class test{
 public static void main(String[] args){
int a=6,b=0;
try{
if(b==0)
throw new ArithmeticException();//抛出异常,因为throw抛出的是异常类所产生的对象,所有要用关键字new
else
System.out.println(a+"/"+b+"="a/b);
}
catch(ArithmeticException e){//e是用来接收异常信息
System.out.println("异常+":"+e+被抛出了");
}
}
}

例子上述中的异常,即使不抛出异常,系统也是会自动抛出的。

  1. 使用throw在方法内抛出异常,此方法不解决异常,使用调用该方法的程序处理异常:

public class test {


publie statie double multi(int n)
{
 if(n<0)
     throw new IllegalArgumentException("求负数阶乘异常");//使用throw语句在方法之中抛出异常
double s=1;
for(inti=1;i<=n;i++)
  s=s*i;
return s;
}


public static void main(String[ ] args){
try{
int m=Integer.parseInt(args 0]);
System.out.println(m+"!="+multi(m));//调用计算阶乘的方法multi()
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("命令行中没提供参数!");
}
catch(NumberFormatException e){
System.out.println("应输入一个【整数】!");
}

catch(IllegalArgumentException e){
System.out.println("出现的异常是:"+e.toString());
}

finally{
System.out.println("程序运行结束!!");
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值