/*
自定义异常:
需求:在本程序中,对于除数是-1,也视为是错误,无法进行运算!
那么就需要对这个问题进行自定义的描述。
当在函数内部出现了throw抛出异常对象,那么就必须要给出对于的处理动作
要么在内部 try catch处理
要么在函数上声明让调用者处理。
一般情况下,函数内出现问题,函数上需要声明。
1.自定义异常必须是自定义类继承Exception.
继承Exception原因:
异常体系有一个特点:因为异常类和异常对象都被抛出。
他们都具备可抛性,这个可抛性是Throwable这个体系中的独有特点。
只有这个体系中的类和对象才可以被throws和throw操作。
*/
public class ExceptionDemo
{
public static void main(String[] args)
{
DemoTest d = new DemoTest();
try
{
int x=d.div(4,-9);
System.out.println("x="+x);
}
catch(FushuException e)
{
System.out.println(e.toString());
System.out.println("错误的负数是:"+e.getValue());
}
System.out.println("over");
}
}
class FushuException extends Exception
{
private int value;
FushuException(String msg,int value)
{
super(msg);
this.value = value;
}
public int getValue()
{
return value;
}
}
class DemoTest
{
int div(int a,int b)throws FushuException
{
if(b<0)
throw new FushuException("除数出现负数啦!",b);
return a/b;
}
} |
|