美文网首页
java常见异常

java常见异常

作者: 一花一世界yu | 来源:发表于2020-04-08 19:30 被阅读0次
/*
 * 一、异常体系结构
 * 
 * java.lang.Throwable
 *      |-----java.lang.Error:一般不编写针对性的代码进行处理。
 *      |-----java.lang.Exception:可以进行异常的处理
 *          |------编译时异常(checked)
 *                  |-----IOException
 *                      |-----FileNotFoundException
 *                  |-----ClassNotFoundException
 *          |------运行时异常(unchecked,RuntimeException)
 *                  |-----NullPointerException
 *                  |-----ArrayIndexOutOfBoundsException
 *                  |-----ClassCastException
 *                  |-----NumberFormatException
 *                  |-----InputMismatchException
 *                  |-----ArithmeticException
 * 面试题常见的异常
 */
public class ExceptionTest {
    //***************以下是编译时异常**************
    //下面是输入流的编译异常
    @Test
    public void test7(){
        try {
            File file = new File("hello.txt");
            FileInputStream fis = new FileInputStream(file);
            int data = fis.read();
            while (data != -1) {
                System.out.print((char) data);
                data = fis.read();
            }
            fis.close();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
    
    
    
    
    
    
    
//********************以下是运行时异常****************
    //ArithmeticException,异常的运算条件
    @Test
    public void test6(){
    int a = 10;
    int sun = a/0;
        
    }
    
    
    
    
    
    //InputMismatchException,控制台输入的与你设置的不匹配
    @Test
    public void test5(){
        Scanner scanner = new Scanner(System.in);
        int socer = scanner.nextInt();
        System.out.println(socer);
        scanner.close();
    }
    
    
    
    
    //NumberFormatException,数字格式化异常
    @Test
    public void test4(){
        String s1 = "abc123";
        int a = Integer.valueOf(s1);
    }
    

    
    //ClassCastException,类型转换异常
    @Test
    public void test3(){
        Object obj = new Date();
        String s1 = (String)obj;
    }
    
    
    //IndexOutOfBoundsException,下标越界异常
    @Test
    public void test2(){
        //StringIndexOutOfBoundsException
//      String name = "abc";
//      System.out.println(name.charAt(3));
        
        //ArrayIndexOutOfBoundsException
        int[] arr = new int[5];
        System.out.println(arr[5]);
        
    }
    
    //NullPointerException,空指针问题
    @Test
    public void test1(){
        //举例一
//      int [] arr = new int [5];
//      arr = null;
//      System.out.println(arr[1]);
        
        //举例二
        String name = "abc";
        name = null;
        System.out.println(name.charAt(0));
    }
}

相关文章

网友评论

      本文标题:java常见异常

      本文链接:https://www.haomeiwen.com/subject/dvlxmhtx.html