package duixiang;
class ZiException extends Exception
{
private int num;
ZiException(String s)
{
super(s);
}
ZiException(String s,int num)
{
super(s);
this.num=num;
}
public int getNum()
{
return num;
}
}
class Demo
{
static int div(int a,int b)throws ZiException//函数上抛出异常,可抛多个
{
if(b<0)
throw new ZiException("fushu",7);//函数体中抛出异常
if(b==0)
throw new ArithmeticException("chuling");//Runtime 的子类,不需要向调用函数抛出异常
return a/b;
}
}
public class YiChanDemo {
public static void main(String [] args)
{
try{
int d= Demo.div(1, -1);
System.out.println(d);
System.out.println("over");
}catch(ZiException e){
System.out.println(e.toString());
System.out.println(e.getNum());
}
catch(ArithmeticException e)
{
System.out.println(e.toString());
}
finally{
System.out.println("Thanks for using!!!");//一定执行的方法区
}
}
}
对象(YiChanDemo)
最新推荐文章于 2025-12-11 22:46:37 发布
本文介绍了一个自定义异常类的实现方式,并通过一个具体的除法运算示例展示了如何使用自定义异常进行错误处理。此外,还展示了如何捕获特定类型的异常并执行清理操作。
691

被折叠的 条评论
为什么被折叠?



