异常的笔记

异常(Exception):

特殊的:RuntimeException(运行期异常,编译时不检查)

其他的异常为编译期异常,编译时报错必须用try-catch否则编译不能通过

try{}catch(){}: 语句块就是用来进行异常处理的

finally{}不管发不发生异常都要执行,在数据库关闭连接的地方有用

try {

                 int num = Integer.parseInt("abc");

                 System.out.println("bbbbbb");

                 System.out.println("cccccc");          

           }catch(Exception e){

                 System.out.println("请输入有效的数字");

            }

            finally {

                System.out.println("bbbbbb");//

            }

           System.out.println("aaaaa");

三种常见的异常

  1. NullPointerException:空指针异常 String str=nill;str.toString();一个引用为空,试图访问方法和属性时出现空指针异常
  2. ArrayIndexOutOfBoundsException数组下标越界异常 public static void main(String args[]){System.out.println(args[0]);}
  3. NumberFormatException   int num=Integer.parseInt(“ddd”)

注意在同一个try-catch里面,必须先捕获子类的异常,在捕获父类的异常

try{

                 int num = Integer.parseInt(args[0]);

           }catch(NumberFormatException e){

                 System.out.println("请输入有效的数字");

           }catch(Exception e){

                 System.out.println("必须输入一个数");

throws关键字:用来把异常抛给调用它的环境

public class Test11a{

      public static void main(String args[]){

try{

                 T.m();

           }catch (Exception e){

                 System.out.println("请输入有效的数字");  

           }

          

      }   

}

class T {

                 public static void m() throws Numbe rFormatException{

                 Integer.parseInt("abc");

             }     

           }

throw 关键字:用来抛出自定义异常的

public class Test11a{

      public static void main(String args[]){

           try{

                 T.m(111);

           }catch(Exception e){

                 System.out.println("请输入1到120之间的数");   

           }

                

      }

}

class T {

      public static void m(int age){

           if(age<=0 || age>=120){

                 throw new AgeException();   

           }

           System.out.println("age:"+age);   

      }   

}

class AgeException extends RuntimeException {

     

}

 

posted @ 2012-07-10 16:26  会飞的辉  阅读(103)  评论(0编辑  收藏  举报