java异常

//这里使用try catch finally语句处理异常的方法,这里是先执行try,catch,finally再到主函数中,如果catch中没有return,就在finally中找。

public class yichangtest {



public static void main(String[] args) {
// TODO Auto-generated method stub
yichangtest a=new yichangtest();
int result=a.test();
System.out.println("test方法执行完毕返回值为"+result);
int result2=a.test2();
System.out.println("test方法执行完毕返回值为"+result2);
}
public int test()
{
int divide=10;
int result=100;
try
{
while(divide>-1)
{
divide--;
result=result+100/divide;

}
return result;
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("循环抛出异常了");
return -1;
}
}
public int test2()
{
int divide=10;
int result=100;
try
{
while(divide>-1)
{
divide--;
result=result+100/divide;

}
return result;
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("循环抛出异常了");
return result=999;
}
finally
{
System.out.println("finally");
System.out.println("result值为"+result);
}

}

//下面添加一个用initcause方法处理异常的方法。test1抛出异常,test2异常并通过initcause抛出异常。主函数调用test2,输出异常信息。实际上这里是test2把test1进行了包装,调用test2就可以调用test1异常。

public class yichnaglian

{


public static void main(String[] args) {
// TODO Auto-generated method stub
yichnaglian a=new yichnaglian();
try{
a.test2();
}catch(Exception e)
{
e.printStackTrace();
}


}
public void test1() throws DrunkException
{
throw new DrunkException("喝酒别开车");
}
public void test2()
{
try{
test1();
}
catch(DrunkException e)
{
RuntimeException newE=new RuntimeException("司机喝酒,亲人流泪");
newE.initCause(e);
throw newE;
}
}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值