Java对所有常见异常的理解

常见异常
Exception分为RuntimeException和no-RuntimeException
RuntimeException(运行时异常):
  1. NullPionterException(空指针异常)

  2. ClassCastException(类型转换异常)

    abstract class Animal{
    	abstract void eat();
    }
     class Cat extends Animal{
        public void eat() {
    		System.out.println("吃鱼");
    	}
     }
    class Dog extends Animal{
        public void eat();{
            System.out.println("吃骨头");
        }
    }
    public class Test{
        public static void main(String[] args) {
    		Animal a=new Cat();   //向上转型
    		a.eat();
    		Cat c=(Cat)a;         //向下转型
    		Dog d=(Dog)a;         //JVM编译时报错
    		d.wat();
    }
  3. IndexOutOfBoundsException(数组下标越界)

  4. IllegalArgumentException(非法参数异常)

    public class Test {
    	public static void main(String[] args) {
    		Date day=new Date();
    	    SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	    System.out.println(df.format(day));//正确,输出系统时间
    	 
    	    String date="2020-05";
    	    System.out.println(df.format(date));//错误。foramte方法里面的参数类型错误
    	}
    
    }
    
  5. ArrayStoreException(数组储存异常)

    public class Test {
    	public static void main(String[] args) {
    	     Son []sons=new Son[3];
    	     Father f=new Father();
    	     sons[0]=(Son) f;  //JVM编译时报错。数组只能存放子类对象
    	}
    }
    class Father{
    
    	public void son() {
    	}	
    }
    class Son extends Father{
    	public void son() {
    		System.out.println("son");
    	}
    }
    
  6. AruthmeticException(算数异常) //0做余数等算数错误

  7. BufferOverflowException(缓冲区溢出异常)

    public class Test {
    	public static void main(String[] args) {
    	    ByteBuffer params=ByteBuffer.allocate(2);//这里只分配了2个字节
    	    params.order(ByteOrder.LITTLE_ENDIAN);
    	    byte[] tmp=new byte[3];
    	    tmp[0]=(byte)1;
    	    tmp[1]=(byte)2;
    	    tmp[2]=(byte)3;
    	    
    	    params.put(tmp);//put的数据两超出,导致出现java.nio.BufferOverflowException 异常
    	}
    }
    
非RuntimeException(检测异常):
  1. IOException(输入输出异常)
    字符流、文件读写时出现的异常

  2. SQLException()

    • 应用程序无法连接数据库
    • 要执行的查询存在语法错误
    • 查询中所使用的表或列不存在
    • 试图插入或更新的数据违反了数据库约束
  3. InterruptedException(中断异常-调用线程睡眠时候)

  4. NumberFormatException(数字格式化异常)

    把String类型转换成其他类型时,输入的String类型格式与这个类型不匹配

    public class Test {
    	public static void main(String[] args) {
    	    int n;
    	    String s="十二";
    	    n=Integer.parseInt(s);
    	}
    }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值