java throws catch_java异常处理throws throw try-catch实例

java异常处理throws throw try-catch实例。throw用于方法中,我们可以预见的错误。

比如:

if(age<0)

{

Exception e = new Exception();//创建异常对象

throw e;//抛出异常

}

在java代码中如果发生异常的话,jvm会抛出异常对象,导致程序代码中断,这个时候jvm在做的操作就是:创建异常对象,然后抛出。

throws用于方法声明时,多种异常用逗号隔开,用于方法中不可预见的异常。例如:

public void funname()throws IOException,SQLException{

}

此种情况可以用try-catch中:

try

{

fun();

}catch(IOException e)

{

}catch(SQLException e)

{

}

写了三个方法,分别举例说明这三种用法:

public static void fun1(){

int age = -1;

if(age<0){

throw new NumberFormatException();

}

System.out.println(“222222222222″);

}

public static void fun2() throws Exception{

String a = “a”;

Integer.parseInt(a);

System.out.println(“11111111111″);

}

public static void fun3(){

int num = 10;

String str = “a”;

for(int i=0;i

try{

Integer.parseInt(str);

}catch(NumberFormatException e){

try {

throw new NumberFormatException(e.toString());

} catch (Exception e1) {

e1.printStackTrace();

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值