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);
}
}