Abnormal exercises:
The teacher uses a computer to teach.
Start thinking about the problems that arise in class.
For example, the problem is
Computer blue screen.
The computer smoked.
To describe the problem, encapsulate it into an object.
However, when smoke occurs, the lecture progress cannot continue.
A question from the instructor emerged: the class schedule cannot be completed.
class Teacher{ private Computer cmp; public void shangKe()throws NoPlanException /*Declare exception*/ { cmp=new Computer(); try { cmp.run(); } catch(LanPingException e) /*Computer catches exception handling blue screen*/ { cmp.recst(); } catch(MaoYanException e) /*Computer catches exception handling computer smoke*/ { throw new NoPlanException("Class cannot continue because "+e.getMessage()); /*Computer cannot handle this exception, continue to throw this exception to the teacher to handle*/ } System.out.println("Teacher class"); /*The teacher will attend class normally without exception*/ }}class LanPingException extends Exception /*Customize blue screen exception*/{ LanPingException(String m) { super(m); }}class MaoYanException extends Exception /*Customize computer smoke exception*/{ MaoYanException(String m) { super(m); }}class NoPlanException extends Exception /*Customize teacher handles exception*/{ NoPlanException(String m) { super(m); }}class Computer{ private int state=3; /*Select different exception status*/ public void run()throws LanPingException,MaoYanException { if(state==2) { throw new LanPingException("Computer is blue screen"); /*Exception object is thrown if the conditions are met*/ } if(state==3) { throw new MaoYanException("Computer is smoking"); } System.out.println("Computer run"); } public void recst() { System.out.println("Computer restart"); }}class ExceptionText{ public static void main(String args[]) { Teacher t=new Teacher(); try { t.shangKe(); } catch(NoPlanException e) /*Teacher catches and handles computer smoke exception*/ { System.out.println(e.toString()); } }}Running results:
NoPlanException: The class cannot continue because the computer is smoking
The above simple exercises for handling java exceptions are all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.