寒假的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);
  }
 }
}

代码执行截图:

 

posted @ 2017-02-12 18:40  Left涅槃  阅读(110)  评论(0编辑  收藏  举报