畢向東——JAVA基礎——異常
阿新 • • 發佈:2019-01-27
1、電腦丟擲問題,老師來處理,處理不了再丟擲
/* 畢老師用電腦上課。 上課中可能出現的問題:電腦藍屏、電腦冒煙。 對問題進行描述,封裝成物件。 冒煙發生後,出現講課無法繼續, 出現了講師問題:課時計劃無法完成。 */ class LanpingException extends Exception{ LanpingException(String message){ super(message); } } class MaoyanException extends Exception{ MaoyanException(String message){ super(message); } } class NoPlanException extends Exception{ NoPlanException(String message){ super(message); } } class Computer{ private int state=3; public void run() throws LanpingException,MaoyanException{ if(state==2) throw new LanpingException("藍屏了"); if(state==3) throw new MaoyanException("冒煙了"); System.out.println("電腦執行"); } public void reset(){ state=1; System.out.println("電腦重啟"); } } class Teacher{ private String name; private Computer cmpt; Teacher(String name){ this.name=name; cmpt=new Computer(); } public void prelect() throws NoPlanException{ try{ cmpt.run(); }catch(LanpingException e){ System.out.println(e.toString()); cmpt.reset(); }catch(MaoyanException e){ System.out.println(e.toString()); test(); throw new NoPlanException("課時計劃無法完成"); } System.out.println("講課"); } public void test(){ System.out.println("做練習"); } } public class ExceptionDemo{ public static void main(String[] args) { Teacher t=new Teacher("畢老師"); try{ t.prelect(); }catch(NoPlanException e){ System.out.println(e.getMessage()); } } }
2、RuntimeException:出現非法值時,程式停止,需要修改輸入
/* 有一個圓形和長方形,都可以獲取面積。 面積如果出現非法數值,視為獲取面積出現問題,用異常表示。 */ class NoValueException extends RuntimeException{ //出現非法值時,之後的操作都不再執行,停止執行 NoValueException(String msg){ super(msg); } } interface Shape{ void getArea(); } class Rec implements Shape{ private int len,wid; Rec(int len,int wid){//throws NoValueException if(len<=0||wid<=0) throw new NoValueException("出現非法值"); this.len=len; this.wid=wid; } @Override public void getArea(){ System.out.println(len*wid); } } class Circle implements Shape{ private int radius; public static final double PI=3.14; Circle(int radius){ if(radius<=0) throw new NoValueException("出現非法值"); this.radius=radius; } @Override public void getArea(){ System.out.println(radius*radius*PI); } } public class ExceptionDemo1{ public static void main(String[] args) { Rec r=new Rec(3,4); r.getArea(); Circle c=new Circle(4); c.getArea(); } }