java 异常处理

异常:

关键字有:throws (声名方法可能要抛出的异常),throw (抛出异常),try (执行可能产生异常的代码),catch (捕获异常),finally(无论发没发生异常,一定会执行的); exception 他是所有异常的父类

下面直接上代码

这是一个字母类

public class Zimu {  

  private String str;

  public Zimu(String str){   

    this.str = str;

  }  

  这里是将抛出异常的代码

  public void pStr() throws Exception{   

    System.out.println(str);   

    for(int i=0;i<str.length();i++)

    {            

    if(!(str.charAt(i) >= 'A' && str.charAt(i) <='Z' )|| !(str.charAt(i)>='a' && str.charAt(i) <= 'z'))    

       throw new Exception("只能是英文字母");  //如果不是字母,我们就抛出的一个异常

    }  

     System.out.println("正确");  }

   }

 public static void main(String[] args) {
  
  try{
   new Person("朱朱朱",45,"女").pSex();
  } //上面这一段是执行可能出现异常的代码
  catch(Exception c){  //这里是抛出异常
   System.out.println("性别错误");
   System.out.println("原因:"+c.getMessage());//这里我们给出了异常原因,拿代码去练习就可以 了
  }

finally{ //这里是不管怎么都会执行的
  System.out.println("over");

}

   }

 

posted @ 2018-05-05 15:18  帅朱朱  阅读(190)  评论(0)    收藏  举报