java异常

来源:互联网 发布:mac版本的greenvpn 编辑:程序博客网 时间:2024/06/05 16:10

//这里使用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