本帖最后由 杨兴庭 于 2013-8-5 18:45 编辑
在毕老师的那个事例里,毕老师设置了一个state 来控制出现的异常,state=2是蓝屏异常,state=3是冒烟异常,
我想通过控制台输入1,2,3来控制异常,这样查看异常种类就只要编译一次了,但我加入 InputStream后他老提示:ExceptionDemo.java:23: 未报告的异常 java.io.IOException;必须对其进行捕捉或声明
以便抛出,我明明已经在run()方法,teach()方法,和主函数方法3个地方把它抛出了,为啥还是这个错误提示。。。。
- <P>import java.io.*;
- class ExceptionDemo
- {
- public static void main(String[] args)throws IOException
- {
- Teacher t = new Teacher("毕老师");</P>
- <P> try
- {
- System.out.println("今天讲课的老师是"+t.getName());
- t.teach();
- }
- catch (StopException e)
- {
- System.out.println("放假,休息一天吧,原因是:"+e.toString());
- }
- }
- }</P>
- <P>class computer
- {
- InputStream in =System.in;
- char ch = (char)in.read();
- public void run() throws BlueException,BoomException,IOException
- {
- if(ch==1)
- throw new BlueException("电脑蓝屏了。。");
- if(ch==2)
- throw new BoomException("电脑爆炸了。。");
- if(ch==3)
- System.out.println("电脑启动,开始上课");
- }</P>
- <P> public void reset()
- {
- System.out.println
- ("电脑开始重新启动。。。。"+"\r\n"+"重启完毕准备开始上课");
- }</P>
- <P>}</P>
- <P>class Teacher
- {
- private String name;
- private computer cp;</P>
- <P> public String getName()
- {
- return name;
- }</P>
- <P> public Teacher(String name)
- {
- this.name = name;
- cp = new computer();
- }</P>
- <P> public void teach()throws StopException,IOException
- {
- try
- {
- cp.run();
- }
- catch (BlueException e)
- {
- System.out.println(e.toString());
- cp.reset();
- }
- catch (BoomException e)
- {
- throw new StopException("电脑炸了,不能讲课了");
- }
- System.out.println("今天我们讲课的内容是。。。。");
- }
- }</P>
- <P>class BlueException extends Exception
- {
- BlueException(String msg)
- {
- super(msg);
- }
- }</P>
- <P>class BoomException extends Exception
- {
- BoomException(String msg)
- {
- super(msg);
- }
- }</P>
- <P>class StopException extends Exception
- {
- StopException(String msg)
- {
- super(msg);
- }
- }
- </P>
复制代码 我想实现控制台输入,要怎么实现?
|