zoukankan      html  css  js  c++  java
  • java常见异常

    运行时异常:指编译器不要求强制处理的异常。一般是指编程时的逻辑错误。java.lang.RuntimeException类及它的子类都是运行时异常。

    下面举例几种常见的运行时异常

    ArrayIndexOutOfBoundsException

    int arr[] = new int[]{1, 2, 3}
    for(int i = 0; i < 4; i++){
        System.out.println(arr[i]);// 数组角标越界异常
    }
    

    数组角标越界异常:指数组的索引取值超过了本身的数组长度,就会造成越界异常

    NullPointerException

    int arr[] = new int[] {1, 2, 3};
    System.out.println(arr[2]);
    arr = null;
    System.out.println(arr[2]);//空指针异常
    

    空指针异常:当取一个null的的索引或调用null的方法和属性时就会产生空指针异常,因为null本身就是空的,调用它的方法或属性是不存在的。

    NumberFormatException

    String str = "123";
    str = "abc";
    Integer i = new Integer(str);	// 数字格式转化错误
    

    数字格式转化异常:当用包装类转化一个由数字组成的字符串时,由于字符串不是由数字组成,所以不知道该转化成什么数字,从而抛出异常

    ClassCastException

    Person p = new Person();
    Student s = (Student)p;	//实例类型转换异常
    
    class Person{}
    class Student extends Person{}
    

    实例类型转换异常:当一对具有子父类关系的类进行类型转换时,如果父类的对象不是多态,那么强制转换为子类类型就会报错,因为并不具有子类的扩展功能

    ArithmeticException

    int a = 10 / 0
    

    算术异常:指一些计算上的错误,零不能做除数

    InputMismatchException

    Scanner scanner = new Scanner(System.in);
    int score = scanner.nextInt();
    System.out.println(score);
    		
    scanner.close();
    

    输入不匹配异常:指在输入过程中,没有输入匹配的数据类型而产生的异常。

    编译时异常:指编译器要求必须处置的异常。即程序在运行时由于外界因素造成的一般性异常。编译器要求Java程序必须捕获或声明所有编译时异常

    FileNotFoundException

    // 文件未找到异常
    File file = new File("hello.txt");
    FileInputStream fileInputStream = new FileInputStream(file);
    

    文件未找到异常:当文件不存在时出现的异常

    异常体系结构

    java.lang.Throwable
     * 		|-----java.lang.Error:一般不编写针对性的代码进行处理。
     * 		|-----java.lang.Exception:可以进行异常的处理
     * 			|------编译时异常(checked)
     * 					|-----IOException
     * 						|-----FileNotFoundException
     * 					|-----ClassNotFoundException
     * 			|------运行时异常(unchecked,RuntimeException)
     * 					|-----NullPointerException
     * 					|-----ArrayIndexOutOfBoundsException
     * 					|-----ClassCastException
     * 					|-----NumberFormatException
     * 					|-----InputMismatchException
     * 					|-----ArithmeticException
    
  • 相关阅读:
    百度地图API
    h5地理位置API
    css3的clip-path属性
    css3的3d属性集合
    模块化之SeaJS(二)
    模块化之SeaJS(一)
    html5制作一个时钟
    闭包论
    UVALive 7066 Intersection(圆环相交面积)
    UVALive 7068 K.Bro Sorting(树状数组求逆序对)
  • 原文地址:https://www.cnblogs.com/welisit/p/11947459.html
Copyright © 2011-2022 走看看