java学习第十课:java异常处理(零基础)

一、异常的类型:
1. Error:没法改变的错误
2. Exception:可以改变的错误
二、程序中的常见异常:
1. ArithmeticExecption 异常-数字运算异常
2. NullPointerExecption 异常-空指针异常
3. NegativeArraySizeExecption 异常-数值大小为负值异常
4. NumberFormatExecption 异常-数字格式异常
5. InputMismatchExecption 异常-输入类型不匹配异常
6. NoSuchMethodExecption 异常-方法不存在异常
7. DataFormatExecption 异常-数据格式错误异常
8. NoClassDefFoundError 错误-未找到类定义错误

三、异常举例:

   (1)int a = 3 / 0;// 1. ArithmeticExecption 异常-数字运算异常
    
    (2)String s=null;
    s.charAt(0);//2. NullPointerExecption 异常-空指针异常
    
    (3)int b[]=new int[-7];//3. NegativeArraySizeExecption 异常-数值大小为负值异常
    
    (4)int c[]=new int[1];
    c[1]=9;//ArrayIndeOutOfBoundsException
    
    (5)String s="32,4";
    double d=Double.valueOf(s);//4. NumberFormatExecption 异常-数字格式异常

  (6)  Scanner sc=new Scanner(System.in);
    int e=sc.nextInt();//6. InputMismatchExecption 异常-输入类型不匹配异常

   (7) A a1=new A();//父类
    B b1=new B();//子类
    b1=(B)a1;//父类转换成子类 强制类型转换 会报错 7.ClassCastException-类转换异常
    
  (8)  A a2=new B();
    b1=(B) a2;//向下转型 可以成功8. DataFormatExecption 异常-数据格式错误异常
}
class A{
    
}
class B extends A{
   }

四、异常处理
1. try-catch-finally 处理异常

package test4;
import java.util.Scanner;
//异常捕获处理异常
public class test2 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int b=sc.nextInt();try {//可能发生异常语句
int a=3/b;//一旦发生异常,后面语句不会执行
System.out.println("test1");
}catch(ArithmeticException e) {
System.out.println("除数不能为 0");
}finally {
System.out.println("test2");
}
System.out.println("test3");
}
}


2. throw 抛出异常
语法格式:throw 异常类对象;
在 throw 语句后立刻终止
(不常用,需最终解决)
四、补充:
1. 多 catch 代码块
如果 try 代码块中有很多语句会发生异常,且异常种类不止一种,try 后面可以跟
多个 catch 代码块。
格式:
Try{
}catch(Throwable e){ }

catch(Throwable e){ }//以此类推


(1) 当一个 catch 代码块捕获一个异常时,其他 catch 代码块不再进行匹配
(2) 当 catch 代码块存在父类和子类异常,先捕获子类异常,再捕获父类异常。

package test4;

import java.util.InputMismatchException;
import java.util.Scanner;

public class test4 {
public static void main(String[] args) {
	Scanner sc =new Scanner(System.in);
	try {
		int flag=sc.nextInt();
		int b=3/flag;
		int c[]=new int[flag];
		c[1]=4;
		String s=null;
		s.charAt(flag);
	}catch(InputMismatchException e) {
		System.out.println("输入不是整型");
	}catch(ArithmeticException e) {
		System.out.println("除数不能为0");
	}catch(NegativeArraySizeException e) {
		System.out.println("不能是负数");
	}
	//或者换成多个 catch(InputMismatchException/ArithmeticException e){
	//System.out.println("输入数据不正确");
//}
}
}


2. 多重捕获
异常种类不同,但处理相同时
格式:
Try{ }catch(AExceptiopn|BException){//这里的 A、B 指不同类型错误
//调用方法处理}
 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值