自定义异常: 除数为负数也看成异常
使用throw抛出异常类对象,必须处理
处理方式有两种
1:使用try{}catch(){}
2: 使用throws 声明可能方法异常
class FuShuException extends Exception
{
public FuShuException(){
super();
}
public FuShuException(String message){
super(message);
}
}
class MyMath
{
public int div(int a,int b)throws FuShuException
{
//因为负数异常在java内部没有定义,所以不会自动创建异常类对象,只能手动创建
//try
//{
if(b<0)
throw new FuShuException("除数为负数了");
//}
//catch (FuShuException e)//FuShuException e = new FuShuException
//{
//e.printStackTrace();
//}
return a/b;
//throw new ArithmeticException();
}
}
class Demo12
{
public static void main(String[] args)
{
MyMath myMath = new MyMath();
try
{
int result = myMath.div(3,-8);//new FuShuException()
System.out.println("result="+result);
}
catch (FuShuException e)//FuShuException e = new FuShuException();
{
System.out.println(e.getMessage());
}
}
}