SoFunction
Updated on 2025-03-09

Simple exercises for java exception handling

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
    {
      ();
    }
    catch(LanPingException e)               /*Computer captures exceptions to handle blue screen*/                   
    {
      ();
    }
    catch(MaoYanException e)                /*Computer captures and handles computer smoking exception*/
    {
      throw new NoPlanException("The class cannot continue because"+());    /*The computer cannot handle this exception, continue to throw this exception to the teacher to handle*/   
    }
    
    ("Teacher teaches");                /*There is no abnormality, the teacher will attend class normally*/
  }
}
class LanPingException extends Exception               /*Custom blue screen exception*/
{
  LanPingException(String m)
  {
    super(m);
  }
}

class MaoYanException extends Exception             /*Custom computer smoke abnormality*/
{
  MaoYanException(String m)
  {
    super(m);
  }
}
class NoPlanException extends Exception             /*Custom teacher handles exceptions*/
{
  NoPlanException(String m)
  {
    super(m);
  }
}

class Computer
{
  private int state=3;           /* Different exception status selection*/
  
  public void run()throws LanPingException,MaoYanException
  {
    if(state==2)                     
    {
      throw new LanPingException("The computer is blue");        /*Exception object is thrown if the conditions are met*/
    }
    if(state==3)
    {
      throw new MaoYanException("The computer is smoking");
    }
    ("Computer running");
  }
  
  
  public void recst()
  {
    ("Computer Restart");
  }
}

class ExceptionText
{
  public static void main(String args[])
  {
    Teacher t=new Teacher();
    try
    {
      ();
    }
    catch(NoPlanException e)               /*The teacher catches and handles computer smoking abnormality*/   
    {
      (());
    }    
  }
}

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 me more.