疯狂java


您现在的位置: 疯狂软件 >> 新闻资讯 >> 正文

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不管发没发生异常都会被执行

  }

  }