/*
自定义异常
*/
class FuShuException extends Exception
{
private String message;//自定义输出信息
FuShuException(String message)
{
this.message=message;
}
public String getMessage()
{
return message;
}
}
class Demo
{
int div(int a,int b)throws FuShuException
{
if(a<0)
throw new FuShuException("出现错误了!");
return a/b;
}
}
class ExceptionDemo
{
public static void main(String[] args)
{
Demo d=new Demo();
try
{
int x=d.div(-4,1);
System.out.println("x="+x);
}
catch (FuShuException e)
{
System.out.println(e.toString());
}
System.out.println("over");
}
}
程序结果:
FuShuException:出现错误了!
over
-----------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
/*
但是上面的自定义语句太麻烦了,我们可以修改成如下语句
*/
/*
自定义异常
*/
class FuShuException extends Exception
{
FuShuException(String message)
{
super(message);//替换成这句super()语句
}
}
class Demo
{
int div(int a,int b)throws FuShuException
{
if(a<0)
throw new FuShuException("出现错误了!-------------");
return a/b;
}
}
class ExceptionDemo
{
public static void main(String[] args)
{
Demo d=new Demo();
try
{
int x=d.div(-4,1);
System.out.println("x="+x);
}
catch (FuShuException e)
{
System.out.println(e.toString());
}
System.out.println("over");
}
}
程序正常运行
备注:因为父类Exception中已经把异常信息操作都完成了。所以子类只要在构造时,将异常信息传递给父类通过super语句就可以直接通过getMessage方法获取自定义的异常信息。下面的代码就解释了这个道理
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
class Person
{
String name;
Person(String name)
{
this.name=name;
}
public String getName()
{
return name;
}
}
class Student extends Person
{
Student(String name)
{
super(name);
}
}
class ExceptionDemo
{
public static void main(String[] args)
{
Student d=new Student("lisi");
System.out.println(d.getName());
}
}
|
|