⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 h.txt

📁 清华本科全套java课件 经典不用多说
💻 TXT
字号:
import java.io.*;

public class a {
  public static void main(String[] args) {
    aaa  a = new aaa();

//-----------test1  方法m1中有异常但不处理-----------------------
    a.m1();      
              
//-----------test2  执行方法m1,捕获异常--------------------------
    try {  a.m1(); }            
    catch (ArrayIndexOutOfBoundsException e)  {
      System.out.println("在main 中捕获方法m1的异常,数组下标越界 ");
    }
    catch (Exception e)  {
      System.out.println("在main 中捕获方法m1的Exception类异常 ");
    }
    System.out.println("异常处理后的语句");
    
//------------test3  方法m2中自己有异常处理------------------------
    a.m2();  
                   
//-----------test4  方法m3有自定义异常 并将异常向外转移-----------
    try {  a.m3(); }           
    catch(MyExp e) {
      System.out.println("异常描述: " + e.getMessage());
      System.out.println("异常对象信息: " + e.toString());
      System.out.println("异常发生过程:");
      e.printStackTrace();
    }


//-----------test5 方法m4利用Exceptio类将异常向外转移-----------
    try {  a.m4(); }            
    catch(Exception e) {
      System.out.println("异常描述: " + e.getMessage());
  }  


 }  // end of main()
}   // end of class a

//---类aaa各方法中,随机制造数组下标越界异常-------------
class aaa {
   private int i;
   private int[] array = {1,2,3,4,5};

  void m1() {
   for (int j=0; j<10; j++) {
      i=(int)(Math.random()*10) ;
      System.out.print("数组下标是:"+ i +"   数组元素是: ");
      System.out.println(array[i]);
   }
  } //end of  m1()

  void m2() {
   try {
       for (int j=0;j<10; j++) {
        i=(int)(Math.random()*10) ;
        System.out.print("数组下标是:"+ i +"   数组元素是: ");
        System.out.println(array[i]);
       }
    }
    catch(ArrayIndexOutOfBoundsException e) {
      System.out.println("在m2方法中出现数组下标越界");
    }

  }  //end of m2()   

  void m3() throws MyExp {
   for (int j=0 ;j<10;j++) {
      i=(int)(Math.random()*10) ;
      if (i>=3) throw  new MyExp("下标太大了");
      System.out.print("数组下标是:"+ i +"   数组元素是: ");
      System.out.println(array[i]);
   }
  }  // end of m3()

  void m4() throws Exception {
   for (int j=0 ;j<10;j++) {
      i=(int)(Math.random()*10) ;
      if (i>=5) throw  new Exception("下标太大了 利用系统例外");
      System.out.print("数组下标是:"+ i +"   数组元素是: ");
      System.out.println(array[i]);
   }
  }   //end of m4()

}  //end of class aaa

class MyExp extends Exception {
  public MyExp(String msg) { super(msg); }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -