大数据-java基础-第13章 使用异常处理程序错误练习

    技术2022-07-12  65

    1.定义一个长方形,属性:长、宽;方法:面积、周长;面积太小抛出无法显示异常。周长过大、抛出超出异常。

    public class Exception03 { private double length; private double weith; public Exception03(double length,double weith) { this.length=length; this.weith=weith; } public void area() { try { if(length*weith <1 || length*weith >1000) { throw new Exception("面积过小或过大无法显示"); } else { System.out.println("面积是:"+length*weith); } }catch(Exception e) { System.out.println(e.getMessage()); } } public void girth() throws Exception{ if((length+weith)*2>2000) { throw new Exception("周长过大物料超出"); }else { System.out.println("周长是:"+(length+weith)*2); } } }

    2.老师在上课,电脑突然冒烟,无法工作,老师的工作无法完成。 ①对象有两个,老师和电脑 ②电脑有冒烟和正常运行两种状态 ③老师有上课行为和必须有电脑。 ④定义冒烟的异常,需要继承exception (1)定义电脑类

    public class Compter { int stat =2;//给定期初电脑状态 public void run() throws BlueException,SmokException{ if(stat==1) { throw new BlueException("电脑蓝屏了!!"); }else if(stat==2) { throw new SmokException("电脑冒烟了!!"); }else { System.out.print("电脑正常运行..."); } } public void restart() { System.out.println("电脑在重启中..."); } }

    (2)定义老师类

    public class Teacher04 { String name; Compter cp =new Compter();//有电脑才能上课 public Teacher04(String name) { this.name=name; } public void teach() throws PeriodException{ try { cp.run(); } catch (BlueException be) { System.out.println(be.getMessage()); cp.restart(); }catch(SmokException se) { System.out.println(se.getMessage()); System.out.println(name+"无法工作"); } } }

    (3)定义冒烟的异常

    public class PeriodException extends Exception{ public PeriodException(String message) { super(message); } }

    (4)测试

    public class TeacherText { public static void main(String []agrs) { Teacher04 t=new Teacher04("李老师"); try { System.out.println(t.name+"正在上课"); t.teach(); } catch (PeriodException pe) { pe.getMessage(); } } }
    Processed: 0.027, SQL: 11