java 如何自定义异常 用代码展示 真心靠谱
先建两个自定义的异常类
ChushufuException类
class ChushufuException extends Exception
{
public ChushufuException(String msg)
{
super(msg);
}
}
ChushulingException
class ChushulingException extends Exception
{
public ChushulingException(String msg)
{
super(msg);
}
}
好了,然后再写一个测试类Numbertest
class Numbertest
{
public int shang(int x,int y) throws ChushulingException,ChushufuException
{
if(y<0)
{
throw new ChushufuException("xxxxxxxxxxx您输入的是"+y+",规定除数不能为负数!");//抛出异常
}
if(y==0)
{
throw new ChushulingException("您输入的是"+y+",除数不能为0!");
}
int m=x/y;
return m;
}
}
是不是很简洁明了?
再来一个测试类
class Rt001 { public static void main(String[]args) throws ChushulingException { Numbertest n=new Numbertest(); Logger logger = Logger.getLogger(Rt001.class.getName()); //捕获异常 try { System.out.println("商="+n.shang(1,-3)); } // catch(ChushulingException yc) // { // System.out.println(yc.getMessage()); // yc.printStackTrace(); // } catch(ChushufuException yx) { System.out.println(yx.getMessage()); yx.printStackTrace(); logger.error("oops, got an exception: ",yx); } // catch(Exception y) // { // System.out.println(y.getMessage()); // y.printStackTrace(); // } //finally{ System.out.println("finally!");} ////finally不管发没发生异常都会被执行 } }
posted on 2013-12-17 15:12 love so much 阅读(403) 评论(0) 编辑 收藏 举报