Java异常捕获的格式:try...catch...finally
代码如下:专注代码块好几天:
class MyMath
{ //此时表示div()方法上如果出现了异常交给被调用处去处理
public static int div(int x ,int y) throws Exception {
int result = 0 ;
System.out.println("***1、除法计算开始 ***") ; //可以理解为把门打开
try
{
result = x/y ;
}
catch (Exception e)
{
throw e ; //继续抛异常
}finally{
System.out.println("***2、除法计算结束 ***") ; //可以理解为把门关上
}
return result ;
}
}
public class TestDemo
{
public static void main(String args[]) {
try
{
System.out.println(MyMath.div(10,0)) ;
}
catch (Exception e)
{
e.printStackTrace() ;
}
}
}
/*
对于以上给出的除法操作不可能永远都正常完成,所以应该进行一些合理的处理,首先如果说
某一个方法出现异常了,必须交给被调用处去处理,那么应该在方法上使用throws抛出。
*/
/*
如果以上代码出错之后,程序中的有些代码就不会执行了,这样明显不太对,经过修改之后,输出结果如下:
***1、除法计算开始 ***
***2、除法计算结束 ***
java.lang.ArithmeticException: / by zero
at MyMath.div(TestDemo.java:8)
at TestDemo.main(TestDemo.java:25)
*/
/*
这段代码理解一下,很重要:
try
{
result = x/y ;
}
catch (Exception e)
{
throw e ; //继续抛异常
}finally{
System.out.println("***2、除法计算结束 ***") ; //可以理解为把门关上
}
*/
/*
实际上以上的代码还可以缩写(把catch省略):
class MyMath
{ //此时表示div()方法上如果出现了异常交给被调用处去处理
public static int div(int x ,int y) throws Exception {
int result = 0 ;
System.out.println("***1、除法计算开始 ***") ; //可以理解为把门打开
try
{
result = x/y ;
}finally{
System.out.println("***2、除法计算结束 ***") ; //可以理解为把门关上
}
return result ;
}
}
public class TestDemo
{
public static void main(String args[]) {
try
{
System.out.println(MyMath.div(10,0)) ;
}
catch (Exception e)
{
e.printStackTrace() ;
}
}
}
*/
/*
如果你直接使用了try...finally,那么表示你连处理一下的机会都没有,就直接给抛出了
*/
运行结果如下:
點擊查看更多內容
4人點贊
評論
評論
共同學習,寫下你的評論
評論加載中...
作者其他優(yōu)質文章
正在加載中
感謝您的支持,我會繼續(xù)努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦