Java 异常处理

来源:互联网 发布:php mysql 扩展 编辑:程序博客网 时间:2024/06/11 03:39

基本格式:

try

{

}

catch(Exception e)

{

        e.printStackTrace();//打印错误信息及位置

}

finally

{

}


自定义异常

(1):RuntimeException     throw

class Test

{

    public static void main(String [] args)

    {

       if(age < 0)

       {

          //声明一个异常对象

          RuntimeException r=new RuntimeException("年龄不能为负数");

          throw r;

        }

       this.age=age;//像这样的情况,年龄为负值是不允许的,就要用到自定义异常

    }

}


(2) Exception throws


class XXX

{

     void  MMM() throws Exception

    {

            if(age<0)

           {

                  Exception e=new Exception("年龄不能为负");

                  throw e;

           }

    }

}


class Test

{

    public static void main(String [] args)

    {

            XXX n=new XXX();

            try

            {

            n.MMM();

            }

            catch(Exception e)

           {

                 e.printStackTrace();

           }

           finally

           {

           }

    }

}