黑马程序员技术交流社区
标题:
有关异常处理的问题
[打印本页]
作者:
filter
时间:
2012-12-15 09:15
标题:
有关异常处理的问题
本帖最后由 李志阳 于 2012-12-15 10:54 编辑
package it.cast;
class FuShuException extends RuntimeException//自定义异常
{ private int num;
FuShuException(String msg,int num)
{
super(msg);//继承父类信息
this.num = num;
}
public int getValue()
{
return num;
}
}
class Demo
{
int div(int a,int b) throws Exception
{
if (b == 0)
throw new Exception("被零除啦!!");//这个异常需要声明并处理
if (b < 0)
throw new FuShuException("除数为负数!!",b);
return a / b;
}
}
class ExceptionDemo4
{
public static void main(String[] args) {
int x = 0;
try {
Demo d = new Demo();
x = d.div(4,-1);
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println(e.toString());
}
// TODO Auto-generated catch block
System.out.println("x = " + x);
}
}
复制代码
有点不太明白,为什么传入4,-1,两个参数,程序不会停止,依然可以运行并打印x=0??出现除数负数的时候不是抛出RuntimeException类异常吗?程序应该停止的啊,求解答:)
作者:
张胜格
时间:
2012-12-15 10:26
我运行了一下确实会抛出异常啊,但是程序遇到异常时并不是停止而是不在执行try块中的代码,所以输出结果是初始值0
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2