java 基础(异常练习)

本文介绍了一个包含自定义异常处理机制的简单程序示例。程序中定义了三个自定义异常类:LpException、SmokeException 和 NoteException,并通过 Computer 类的 run 方法抛出。Teacher 类尝试运行 Computer 并捕获异常,如果捕获到 SmokeException,则会进一步抛出 NoteException。最后在 main 方法中调用 Teacher 类并处理 NoteException。
class LpException extends Exception
{
	LpException(String message)
	{
		super(message);
	}
}

class SmokeException extends Exception
{
	SmokeException(String message)
	{
		super(message);
	}
}

class NoteException extends Exception
{
	NoteException(String message){
		super(message);
	}
}

class Computer
{ 
	private int state=3; 
	void run()throws LpException,SmokeException
	{	
		System.out.println("start");
		if(state==2)
			throw new LpException("langpin");
		if(state==3)
			throw new SmokeException("smoke");	
	}
	void close()
	{ 
		state=1;
		System.out.println("stop");
	}
}

class Teacher 
{
	private String name;
	Computer pc;
	Teacher(String name)
	{
		this.name =name;
		pc=new Computer();
		
	}
	void teaching()throws NoteException
	{
		try
		{
			pc.run();
		}
		catch(LpException e)
		{
			pc.close();
		}
		catch(SmokeException e)
		{
			test();
			throw new NoteException(e.getMessage()+"  break");
		}
		System.out.println("teaching");
	}
	void test()
	{
		System.out.println("testing");
	}
	
}

class MI
{
	public static void main(String[] args)
	{
		Teacher t=new Teacher("bi");
		try
		{
			t.teaching();
		}
		catch(NoteException e)
		{
			System.out.println(e.toString());
			System.out.println("change");
		}
	}
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值