黑马程序员技术交流社区
标题:
要不要加throws Exception
[打印本页]
作者:
张钧杰
时间:
2012-3-21 23:52
标题:
要不要加throws Exception
class Demo
{
int div(int a,int b)
throws Exception
{
return a/b;
}
}
class ExceptionDemo
{
public static void main(String[] agrs)
throws Exception
{
Demo d = new Demo();
int x = d.div(4,0);
System.out.println("x="+x);
System.out.println("over");
}
}
和
class Demo
{
int div(int a,int b)
{
return a/b;
}
}
class ExceptionDemo
{
public static void main(String[] agrs)
{
Demo d = new Demo();
int x = d.div(4,0);
System.out.println("x="+x);
System.out.println("over");
}
}
执行程序都一样的报错,报错内容都一样,要不要加上throws Exception?
作者:
张一凡
时间:
2012-3-21 23:54
你的主函数也要抛的,主函数抛给虚拟机,给虚拟机去处理。
当然如果你抛的是RuntimeException异常就不需要。
作者:
吕猛
时间:
2012-3-22 00:01
哥们,这不是异常不异常的问题。0不能做除数。只能让程序停下来,或者try一下,让程序跳转。
作者:
田斌
时间:
2012-3-22 00:05
把异常抛出 然后自己手动try catch 处理,捕捉到异常
作者:
田斌
时间:
2012-3-22 00:08
本帖最后由 田斌 于 2012-3-22 00:09 编辑
int x = d.div(4,0);
try
{
int x = d.div(4,0);
}
catch(Exception e){
System.out.println("被除数不能为零");
}
作者:
蒙武辉
时间:
2012-3-22 00:14
当然要抛异常,不然怎么运行。
作者:
张明星
时间:
2012-3-22 00:26
这是因为int x = d.div (4 , 0) ,零作为除数了,虚拟机会抛出ArithmeticException:/ by zero的异常,为此需要捕获异常。只需要在主函数中
try
{
int x = d.div(4,0);
System.out.println("x="+x);
System.out.println("over");
}
catch (ArithmeticException e)
{
System.out.println("除零了");
}
即可。当然,将ArithmeticException替换为Exception也可以。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2