zoukankan      html  css  js  c++  java
  • 寒假的Java学习笔记总结2

    异常处理

    1.异常处理语法

    try

    {要检查的程序语句;}

    catch( Exception e)(注:异常类 对象名称 常用Exception e)

    {异常发生时的吃力语句;}

    finally

    {一定会执行到的程序代码;}

    应用代码:

    public class Java0 {

     public static void main(String args[])
     {
      try                        //检查这个程序块的代码
      {
       int arr[]=new int [5];
       arr[10]=7;             //这里会出现异常
      }
      catch(ArrayIndexOutOfBoundsException e)
      {
       System.out.println("数组超出绑定范围!");
      }
      finally                    //这块程序代码一定会被执行
      {
       System.out.println("这里一定会被执行!");
      }
      System.out.println("main()方法结束!");
     }
    }

    代码截图:

    2.抛出异常语法

    try

    {if()

    throws new Exception("处理语句");}

    catch

    {System.out.println(e):}

    应用代码:

    //在程序中抛出异常
    public class Java2 {
     public static void main(String args[])
     {
      int a=4,b=0;
     try
     {
      if(b==0)
       throw new Exception("一个算术异常");//抛出异常
      else
       System.out.println(a+"/"+b+"="+a/b);
     }
     catch(Exception e)
     {
      System.out.println("抛出异常为:"+e);
     }
     }

    }

    代码截图:

    3.编写自己的异常类

    class 异常类名称 extends Exception

    {...

    super();//调用父类的构造方法。};

    eg:编写自己的异常类Cuo,然后调用

    //除0操作的程序,使程序抛出异常,并输出“被除数为0,程序错误。”
    class Cuo extends Exception
    {
     public Cuo(String cuo)
     {
      super(cuo);
     }
    }
    public class Java5 {
     public static void main(String args[])
     {
      int a=5,b=0;
      try
      {
       if(b==0)
       {
        throw new Cuo("被除数为0,程序错误!");
       }
       else
       {
        System.out.println("两数之商为:"+a/b);
       }
      }
      catch(Cuo e)
      {
       System.out.println(e);
      }
     }
    }

    代码执行截图:

  • 相关阅读:
    LeetCode 258 Add Digits
    LeetCode 231 Power of Two
    LeetCode 28 Implement strStr()
    LeetCode 26 Remove Duplicates from Sorted Array
    LeetCode 21 Merge Two Sorted Lists
    LeetCode 20 Valid Parentheses
    图形处理函数库 ImageTTFBBox
    php一些函数
    func_get_arg(),func_get_args()和func_num_args()的用法
    人生不是故事,人生是世故,摸爬滚打才不会辜负功名尘土
  • 原文地址:https://www.cnblogs.com/CkmIT/p/6391511.html
Copyright © 2011-2022 走看看