Java自定义异常_动力节点Java学院整理
废话不多说了,直接给大家贴代码了,具体代码如下所示:
/*下面做了归纳总结,欢迎批评指正*/
/*自定义异常*/
classChushulingExceptionextendsException
{
publicChushulingException(Stringmsg)
{
super(msg);
}
}
classChushufuExceptionextendsException
{
publicChushufuException(Stringmsg)
{
super(msg);
}
}
/*自定义异常End*/
classNumbertest
{
publicintshang(intx,inty)throwsChushulingException,ChushufuException
{
if(y<0)
{
thrownewChushufuException("您输入的是"+y+",规定除数不能为负数!");//抛出异常
}
if(y==0)
{
thrownewChushulingException("您输入的是"+y+",除数不能为0!");
}
intm=x/y;
returnm;
}
}
classRt001
{
publicstaticvoidmain(String[]args)
{
Numbertestn=newNumbertest();
//捕获异常
try
{
System.out.println("商="+n.shang(1,-3));
}
catch(ChushulingExceptionyc)
{
System.out.println(yc.getMessage());
yc.printStackTrace();
}
catch(ChushufuExceptionyx)
{
System.out.println(yx.getMessage());
yx.printStackTrace();
}
catch(Exceptiony)
{
System.out.println(y.getMessage());
y.printStackTrace();
}
finally{System.out.println("finally!");}////finally不管发没发生异常都会被执行
}
}
/*
[总结]
1.自定义异常:
class异常类名extendsException
{
public异常类名(Stringmsg)
{
super(msg);
}
}
2.标识可能抛出的异常:
throws异常类名1,异常类名2
3.捕获异常:
try{}
catch(异常类名y){}
catch(异常类名y){}
4.方法解释
getMessage()//输出异常的信息
printStackTrace()//输出导致异常更为详细的信息
*/
以上所述是小编给大家介绍的Java自定义异常_动力节点Java学院整理,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!