自定义异常

来源:互联网 发布:线切割操作方法编程 编辑:程序博客网 时间:2024/06/11 20:45
/*
 *自定义异常
 *需求:定义一个异常类,对于除数的负数也视为是错的
 *@朱市
 * */
class Demo
{
 int div(int a,int b)throws FuShuException
 {
  if(b<0)
   throw new FuShuException("chushushifushu /by fushu",b);
  return a/b;
 }
}
class FuShuException extends Exception
{
 private int value;//记录该负数的值
 FuShuException(String message,int value)
 {
  super(message);//调用父类构造函数
  this.value=value;
 }
 public int getValue()
 {
  return value;
 }
}
public class Day1
{
 public static void main(String[] args)
 {
  Demo d=new Demo();
  try
  {
   int x=d.div(5, -3);
   System.out.println("x="+x);  
  }
  catch(FuShuException e)
  {
   System.out.println(e.toString()); 
   System.out.println("the fushi is  "+e.getValue());
  }
  
 }
}
0 0