异常Exception:异常不是错,是意外
异常分类
运行异常(未检查异常):可处理,可不处理
RuntimeException以及子类都为运行异常
编译异常(检查异常):必须处理
Exception以及子类(不包括RuntimeException)都是编译异常
异常处理
两种处理方式:
1、抛出异常 throws
在方法名后 抛出 throws 异常类型
2、try。。。catch处理
try{
可能出现异常的代码块;
}catch(异常类型 异常对象){
//异常处理
}finally{//可以没有finally
//保证必须执行的代码
}
自定义异常
定义异常:
1、创建类 继承异常类
2、通过构造函数 构造新的异常信息
使用自定义异常:
throw 异常对象
常见异常:
ArithmeticException:算术异常
ArrayIndexOutOfBoundsException:下标索引越界
NullPointerException:空指针异常(对象是空的)
ParseException:解析异常
public static void main(String[] args) {
// try {
// System.out.println(10/2);
// } catch (Exception e) {//这里写处理异常的代码
// //错误输出流
// System.err.println("0不能做被除数");
// }finally {
// System.out.println("这里的代码必须执行");
// }
// System.out.println("嘿嘿嘿");
System.out.println("===================");
// try {
// int[] a = new int[5];
// System.out.println(a[1]);
// } catch (Exception e) {
// System.out.println("下标越界");
// }
Scanner sc = new Scanner(System.in);
try {
int a = sc.nextInt();
System.out.println(a);
} catch (Exception e) {
System.out.println("你似不似傻,输入整数好不啦");
}
}