2015.9.15 自定义异常的完整练习

来源:互联网 发布:四维星设计软件 编辑:程序博客网 时间:2024/06/05 03:46
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
class Personexception extends Exception  //自定义异常,继承自异常类
{
public Personexception(String name) throws IOException   //类的构造方法,被实例化的时候就执行方法体里的语句
{
System.out.println("我叫"+name+"我的健康状况是良好的,我肯定是意外死亡,请帮我报警,谢谢,九泉之下铭记大恩大德!");
File f = new File("c:/demofolder" + File.separator+"testoutput.txt");  //硬盘上一定要有C:\demofolder这个目录
         OutputStream out=new FileOutputStream(f);//如果文件不存在会自动创建
         String str=("我叫"+name+"我的健康状况是良好的,我肯定是意外死亡,请帮我报警,谢谢,九泉之下铭记大恩大德!");
         byte[] b=str.getBytes();
         out.write(b);//因为是字节流,所以要转化成字节数组进行输出
         out.close();
}
}


class Person //定义一个Person类
{
  private String name;     //人的名字
  private String healthstatus;  //人的健康状态
  public Person(String name,String healthstatus)  //构造方法,给一个人赋值名字,和健康状态
  {
this.name=name;
this.healthstatus=healthstatus;
  }


  public void dead() throws Personexception //Person类的死亡方法,有可能抛出异常
, IOException
  {
if(this.healthstatus.equals("good")) // 如果健康状况是良好,就抛出异常
{
throw new Personexception(this.name);//用 throw 关键字抛出异常
}
else  //执行别的代码
{
System.out.println("身体状况一直很差,我八成是病死的,请把我的骨灰洒向大海,谢谢!");
}
  }
}


public class PersonExceptionTest {   //测试类,主类,要与文件名一致
public static void main(String[] args) throws Personexception, IOException
{
Person firstman=new Person("Jack","poor");  //实例化第一个人对象,健康状况差,死亡不抛出异常
try
{
firstman.dead();
}
catch (Personexception e)
{
System.out.println("有异常发生,这个人死前有话说");
}
Person secondman=new Person("Tom","good"); //实例化第二个对象,健康状体是良好,死亡出发异常
try
{
secondman.dead();
}
catch (Personexception e)
{
System.out.println("有异常发生,这个人死前有话说");
}
Person thirdman=new Person("Bob","poor");
try
{
thirdman.dead();
}
finally  
{
System.out.println("代码执行完毕");
}
}
}
0 0
原创粉丝点击