class NegativeException extends ArithmeticException
{
NegativeException(String msg)
{
super(msg);
}
}
//若在方法体中抛出非RuntimeException,而在方法上没有声明该异常,则发生编译错误
class Div
{
int div(int a,int b)
{
if(b<0)
throw new NegativeException("除数是负数");
else if(b==0)
throw new RuntimeException("除以了0");
else
return a/b;
}
}
class RuntimeDemo
{
public static void main(String[] args)
{
Div d=new Div();
d.div(4,0);
}
}
Java day08 异常(2)
最新推荐文章于 2024-03-17 16:28:32 发布
本文通过Java代码展示了如何在方法中处理异常,特别是当抛出非RuntimeException时的方法,以及如何正确地声明和捕获这些异常。通过实例演示了在方法体中抛出异常的场景,并解释了在方法声明时未声明异常时发生的编译错误。
1373

被折叠的 条评论
为什么被折叠?



