标签:
在本程序中,对于除数是-1,也视为是错误的,是无法进行运算的。class FuShuException extends Exception
{
/*private String msg;
FuShuException(String msg)
{
this.msg=msg;
}
public String getMessage()
{
return msg;
}*/
int num;
FuShuException()
{
super();//空参数的构造函数。
}
FuShuException(String name,int num)
{
super(name);//通过super语句将异常信息传递给父类
this.num=num;
}
public void show()
{
System.out.println("除数的值:"+num);
}
}
class Demo
{
public int function(int a,int b) throws FuShuException //这个函数有可能会出现异常,某个函数在调用该函数时需要抛出异常(throws)或对异常进行处理(try...catch)。
{
int[] arr=new int[a];
if (b<0)
{
throw new FuShuException("除数出现了小于零的情况",b);//如果满足条件则抛出异常信息。
}
return a/b;
}
}
class ExceptionClassDemo1
{
public static void main(String args[]) //throws FuShuException ——这是抛出异常,即编译时不会报错,在运行时虚拟机会提示异常信息。
{
Demo de=new Demo();
//下面的代码对异常进行处理。
try
{
int result=de.function(5,-1);
System.out.println(result);
}
catch (FuShuException e)
{
System.out.println(e.getMessage());
e.show();
}
/*
int result=de.function(5,-1);
System.out.println(result);
*/
}
}标签:
原文地址:http://blog.csdn.net/iemdm1110/article/details/51356796