自定义异常,并将异常对象写入文件

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;


class Personexception extends Exception  //自定义异常,继承自异常类
{
public Personexception(String name) throws IOException //类的构造方法,被实例化的时候就执行方法体里的语句
{

System.out.println("我叫"+name+"我的健康状况是良好的,我肯定是意外死亡,请帮我报警,谢谢,九泉之下铭记大恩大德!");
File f = new File("c:/demofolder/testoutput.txt");
        Writer out=new FileWriter(f);
        String str=("我叫"+name+"我的健康状况是良好的,我肯定是意外死亡,请帮我报警,谢谢,九泉之下铭记大恩大德!");
        out.write(str);
        //out.flush();
        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,IOException //Person类的死亡方法,有可能抛出异常
  {
if(this.healthstatus.equals("good")) // 如果健康状况是良好,就抛出异常
{
throw new Personexception(this.name); //用 throw 关键字抛出异常
}
else  //执行别的代码
{
System.out.println("我叫"+name+"身体状况一直很差,我八成是病死的,请把我的骨灰洒向大海,谢谢!");
}
  }
}


public class Test2 {   //测试类,主类,要与文件名一致
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("代码执行完毕");
}
}
}











评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值