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");
}
}
}java 基础(异常练习)
最新推荐文章于 2021-04-12 14:11:54 发布
本文介绍了一个包含自定义异常处理机制的简单程序示例。程序中定义了三个自定义异常类:LpException、SmokeException 和 NoteException,并通过 Computer 类的 run 方法抛出。Teacher 类尝试运行 Computer 并捕获异常,如果捕获到 SmokeException,则会进一步抛出 NoteException。最后在 main 方法中调用 Teacher 类并处理 NoteException。
2068

被折叠的 条评论
为什么被折叠?



