java自定义异常处理类
MyException继承RuntimeException,业务层thorwMyException,控制层捕获类型匹配不到MyException,只能用RuntimeEx...
MyException继承RuntimeException,业务层thorw MyException,控制层捕获类型匹配不到MyException,只能用RuntimeException匹配。我想用MyException匹配啊。别说继承Exception,因为我不想每个业务方法上写一个thorws
展开
2017-07-12 · 百度知道合伙人官方认证企业
育知同创教育
1【专注:Python+人工智能|Java大数据|HTML5培训】 2【免费提供名师直播课堂、公开课及视频教程】 3【地址:北京市昌平区三旗百汇物美大卖场2层,微信公众号:yuzhitc】
向TA提问
关注
展开全部
[java] view plain copy print?
/*下面做了归纳总结,欢迎批评指正*/
/*自定义异常*/
class ChushulingException extends Exception
{
public ChushulingException(String msg)
{
super(msg);
}
}
class ChushufuException extends Exception
{
public ChushufuException(String msg)
{
super(msg);
}
}
/*自定义异常 End*/
class Numbertest
{
public int shang(int x,int y) throws ChushulingException,ChushufuException
{
if(y<0)
{
throw new ChushufuException("您输入的是"+y+",规定除数不能为负数!");//抛出异常
}
if(y==0)
{
throw new ChushulingException("您输入的是"+y+",除数不能为0!");
}
int m=x/y;
return m;
}
}
class Rt001
{
public static void main(String[]args)
{
Numbertest n=new Numbertest();
//捕获异常
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();
}
catch(Exception y)
{
System.out.println(y.getMessage());
y.printStackTrace();
}
finally{ System.out.println("finally!");} ////finally不管发没发生异常都会被执行
}
}
/*
[总结]
1.自定义异常:
class 异常类名 extends Exception
{
public 异常类名(String msg)
{
super(msg);
}
}
2.标识可能抛出的异常:
throws 异常类名1,异常类名2
3.捕获异常:
try{}
catch(异常类名 y){}
catch(异常类名 y){}
4.方法解释
getMessage() //输出异常的信息
printStackTrace() //输出导致异常更为详细的信息
*/
/*下面做了归纳总结,欢迎批评指正*/
/*自定义异常*/
class ChushulingException extends Exception
{
public ChushulingException(String msg)
{
super(msg);
}
}
class ChushufuException extends Exception
{
public ChushufuException(String msg)
{
super(msg);
}
}
/*自定义异常 End*/
class Numbertest
{
public int shang(int x,int y) throws ChushulingException,ChushufuException
{
if(y<0)
{
throw new ChushufuException("您输入的是"+y+",规定除数不能为负数!");//抛出异常
}
if(y==0)
{
throw new ChushulingException("您输入的是"+y+",除数不能为0!");
}
int m=x/y;
return m;
}
}
class Rt001
{
public static void main(String[]args)
{
Numbertest n=new Numbertest();
//捕获异常
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();
}
catch(Exception y)
{
System.out.println(y.getMessage());
y.printStackTrace();
}
finally{ System.out.println("finally!");} ////finally不管发没发生异常都会被执行
}
}
/*
[总结]
1.自定义异常:
class 异常类名 extends Exception
{
public 异常类名(String msg)
{
super(msg);
}
}
2.标识可能抛出的异常:
throws 异常类名1,异常类名2
3.捕获异常:
try{}
catch(异常类名 y){}
catch(异常类名 y){}
4.方法解释
getMessage() //输出异常的信息
printStackTrace() //输出导致异常更为详细的信息
*/
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询