一、什么是异常
程序在运行过程中出现的不正常现象,它会终止正在运行的程序。
二、异常处理的方案
1.抓住异常:try catch finally
try:可能产生异常的代码块 必须写,并且写一个,在最上边写
catch:对一类异常的处理方案 可以省略 也可以书写多个
finally:总会执行的代码块 可以省略 只能书写一个 在最后写
//异常捕捉情况一
public static void c1(){
System.out.println("请输入一个数");
int a=0;
try{
a = in.nextInt();
}catch(InputMismatchException e){
System.out.println(e.getMessage());//输出的得到的信息
e.printStackTrace();//错误的一段信息 在命令行打印异常信息在程序中出错的位置及原因
}
System.out.println(a);
}
//情况四
public static void c3(){
try {//异常产生后,后面的代码将不会执行
System.out.println("请输入一个数:");
int a = in.nextInt();
int result = 9/a;
System.out.println(result);
}catch (InputMismatchException e){//多异常的话 会自上向下匹配 只产生一种异常
System.out.println("你输入的不是数字!");
}catch (ArithmeticException e){
System.out.println("除数不能为零!");
}
System.out.println("异常外的内容!");
}
//情况五
public static void c4(){
System.out.println("请输入一个数:");
int a = 0;
try{
a = in.nextInt();
}catch (NullPointerException e){
System.out.println("你的代码异常!");
}finally {//总会执行
System.out.println("总会执行的代码块!");
}
System.out.println(a);
}
//抓住异常
public class DemoB {
private static Scanner in = new Scanner(System.in);
//多catch块的情况下,应该先子类后父类,因为子类更具体,父类更通用
public static void a(){
try {
String str = "as";
int i = 9 / 0;
char a = str.charAt(3);
}catch (Exception e){
System.out.println("产生异常");
}/*catch(StringIndexOutOfBoundsException e){//报错
System.out.println("下标越界");
}catch(ArithmeticException e){
System.out.println("算术异常");
}*/
System.out.println("OK!");
}
}
public static int c(){
try{
return 5;
}finally {
return 6;
}//输出6 因为finally肯定会执行
}
public static void main(String[] args) {
System.out.println(c());//输出5 和6
}//有异常没异常 抓住了 没抓住 都看finally
/*
Error:错误,程序在运行过程中出现的错误,程序员无法处理,程序外的东西 比如:内存溢出,没网
Exception:异常,程序在运行过程中的不正常现象,导致程序终止 bug
Throwable:是上面两个的父类
*/
2.抛出异常
//异常---抛出异常 throw throws
// throws总是出现在一个函数头中,用来标明该成员函数可能抛出的各种异常
//throw总是出现在函数体中,用来抛出一个异常
//throw 是语句抛出一个异常;throws 是方法抛出一个异常
//
public class DemoC {
public void a(int len) throws Exception{
if(len>10){
throw new Exception();
}
}
public void b() throws Exception{
a(4);
}
public void c(){
try{
b();
}catch (Exception e){
System.out.println("不能输入一个大于10的数!");
}
}
//处理异常 或者 继续传递异常(即继续抛出异常)
public static void main(String[] args) {
new DemoC().c();
}
}
三、异常的分类
1.异常的最大父类是:Exception,也可以这样去说Exception可以标注所有异常
2.异常分为:
(1)运行时异常(RuntimeException):编译能通过,运行时出现异常。
(2)编译时异常:编译时出现异常。
(3)常见异常:
①ArithmeticException(数学/算术异常):不符合Java中的数学运算语法,最常见的是除零
②NullPointerException(空指针异常):试图使用一个空对象的属性和方法
③ArrayIndexOutBoundsException(数组索引越界):超出了数组长度
④InputMismatchException(输入类型异常):输入的类型和接收的类型不一致
⑤StringIndexOutOfBoundsException(字符串索引越界异常):超出了字符串索引长度
⑥NumberFormatException(数字转换异常):试图将一个非数字数据转换成数字