异常exception

  throwable(可以抛出的)

     1.error()致命的错误,不可以恢复的(java虚拟机报错不能修复)

     2.exception()异常,代码写错了

        exception()2种

        1.编译期异常    (编译器时报异常)编译时需要检查,并且一定要写  try-catch

        2.运行时异常     (编译时不报异常,运行时报异常)(特殊的一个)(编译时不检查,写不写try-catch都通过)

                     RuntimeException()

                                    IndexOutOfBoundsException()

ArrayIndexOutOfBoundsException()               StringIndexOutOfBoundsException()

例子try{ 

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

      System.out.println("11");

       int num2 = Integer.praseInt(args[1]);

       System.out.println(num1+num2);

}catch(NumberFormatException e){

        System.out.println(请输入合法的整数);

      }

try中若其中有一句语句报错,后面的不会执行 

try若不报异常 则catch不会执行

finally{

}(try里不管报不报异常都执行)

 

常用的运行时异常

    驼峰命名法(单词的第一个字母大写)

NumberFormatException

ArrayIndexOutOfBoundsException

NullPointException(当一个引用的值为NULL的时候试图用它来调用方法或访问属性就会发生空指针异常)

String str;

str = new String("abc");

str = null;

str.length();

多个异常用catch捕获

catch(Exction.e)所有的异常都捕获

try-catch可以捕获多个异常 但需要捕获子类的异常,再捕获父类的异常(所以最好分开写)

throws关键字

把异常抛给调用他的环境

 

throw  手动抛出异常,自定义异常

 

在方法上写throws不用在方法里写try-catch

例子:

class penson{

    int age;

    public void setAge(int age){

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

              throw new MyAgeException("年龄必须在0到120之间");

          }

          this.age = age;

     }

}

class MyAgeException extends RuntimeException{

   public MyAgeException(String msg){

        super(msg);

    }

}

转载于:https://www.cnblogs.com/bod08xiongluyao/archive/2013/02/23/2922960.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值