java中check和uncheck异常处理

有两种类型的异常:一种是checked异常一种是unchecked异常,在这篇文章中我们将利用实例来学习这两种异常,checked的异常和unchecked异常最大的区别就是checked去唱是在编译时检查的而unchecked异常是在运行时检查的。

什么是checked异常呢?

checked异常在编译时检查,这意味着如果一个方法抛出checked异常,那么它应该使用try-catch块或者使用throws关键字来处理这个异常,否则的话程序会报编译错误,命名为checked异常是因为是在编译时checked的。

用例子来理解这个问题,在这个例子中,我们读取myfile.txt这个文件并且将它的内容输出到屏幕上,在下边这个程序中有三处异常被抛出。FileInputStream使用了指定的文件路径和名称,抛出FileNotFoundException,这个读取文件内容的read()函数抛出IOException异常,关闭文件输入流的close()函数同样也抛出IOException异常。

[java]  view plain  copy
  1. import java.io.*;  
  2. class Example {    
  3.    public static void main(String args[])   
  4.    {  
  5.     FileInputStream fis = null;  
  6.     /*This constructor FileInputStream(File filename) 
  7.      * throws FileNotFoundException which is a checked 
  8.      * exception*/  
  9.         fis = new FileInputStream("B:/myfile.txt");   
  10.     int k;   
  11.   
  12.     /*Method read() of FileInputStream class also throws  
  13.      * a checked exception: IOException*/  
  14.     while(( k = fis.read() ) != -1)   
  15.     {   
  16.         System.out.print((char)k);   
  17.     }   
  18.   
  19.     /*The method close() closes the file input stream 
  20.      * It throws IOException*/  
  21.     fis.close();      
  22.    }  
  23. }  

输出的结果:

[plain]  view plain  copy
  1. Exception in thread "main" java.lang.Error: Unresolved compilation problems:   
  2. Unhandled exception type FileNotFoundException  
  3. Unhandled exception type IOException  
  4. Unhandled exception type IOException  

为什么这个会编译错误呢?像我在一开始提到的checked异常在编译时被检查,因为我们没有处理这些异常,我们的编译程序报出了编译错误。

怎么解决这个错误呢?有两种方式避免这种错误,我们一条一条的来看:

方法一:使用throws关键字声明异常

我们知道在main()函数里有三个checked异常发生,那么避免这种编译错误的一种方式就是:在方法上使用throws关键字声明一个异常,你或许会想我们的代码抛出FileNotFoundException和IOEXception,为什么我们是声明了一个IOException呢,原因是IOException是FileNotFoundException的父类,前者默认覆盖了后者,如果你想你也可以这样声明异常:

[java]  view plain  copy
  1. public static void main(String args[]) throws IOException, FileNotFoundException.  

[java]  view plain  copy
  1. import java.io.*;  
  2. class Example {    
  3.    public static void main(String args[]) throws IOException  
  4.    {  
  5.       FileInputStream fis = null;  
  6.       fis = new FileInputStream("B:/myfile.txt");   
  7.       int k;   
  8.   
  9.       while(( k = fis.read() ) != -1)   
  10.       {   
  11.        System.out.print((char)k);   
  12.       }   
  13.       fis.close();    
  14.    }  
  15. }  

输出结果:

File content is displayed on the screen.

方法二:使用try-catch块处理异常

上一种方法并不是很好,那不是处理异常最好的方式,你应该对每一个异常给出有意义的信息,使那些想了解这些错误的人能够理解,下边是这样的代码:

[java]  view plain  copy
  1. import java.io.*;  
  2. class Example {    
  3.    public static void main(String args[])  
  4.    {  
  5.     FileInputStream fis = null;  
  6.     try{  
  7.         fis = new FileInputStream("B:/myfile.txt");   
  8.     }catch(FileNotFoundException fnfe){  
  9.             System.out.println("The specified file is not " +  
  10.             "present at the given path");  
  11.      }  
  12.     int k;   
  13.     try{  
  14.         while(( k = fis.read() ) != -1)   
  15.         {   
  16.         System.out.print((char)k);   
  17.         }   
  18.         fis.close();   
  19.     }catch(IOException ioe){  
  20.         System.out.println("I/O error occurred: "+ioe);  
  21.      }  
  22.    }  
  23. }  


上边的代码能够正常运行,并将内容显示出来

下边是一些其他的checked异常

SQLException

IOEXception

DataAccessException

ClassNotFoundException

InvocationTargetException

什么是unchecked异常呢

unchecked异常在编译时不会检查,这意味着即使你没有声明或者处理异常你的程序也会抛出一个unchecked异常,程序不会给出一个编译错误,大多数情况下这些异常的发生是由于用户在交互过程中提供的坏数据。这需要程序员提前去判断这种能够产生这种异常的情况并且恰当的处理它。所有的unchecked异常都是RuntimeException的子类。

我们来看一下下边的代码:

[java]  view plain  copy
  1. class Example {    
  2.    public static void main(String args[])  
  3.    {  
  4.     int num1=10;  
  5.     int num2=0;  
  6.     /*Since I'm dividing an integer with 0 
  7.      * it should throw ArithmeticException*/  
  8.     int res=num1/num2;  
  9.     System.out.println(res);  
  10.    }  
  11. }  

如果你编译这段代码,这段代码将会被通过,但是当你运行的时候它将抛出ArithmeticException。这段代码清楚的表明了unchecked异常在编译期间是不会被checked的,他们在运行期间被检查,我们来看另一个例子:

[java]  view plain  copy
  1. class Example {    
  2.    public static void main(String args[])  
  3.    {  
  4.     int arr[] ={1,2,3,4,5};  
  5.     /*My array has only 5 elements but 
  6.      * I'm trying to display the value of  
  7.      * 8th element. It should throw 
  8.      * ArrayIndexOutOfBoundsException*/  
  9.     System.out.println(arr[7]);  
  10.    }  
  11. }  

这段代码同样被成功的编译通过,因为ArrayIndexOutOfBoundsException是unchecked异常。

注意:这并不意味着编译器不检查这些异常我们就不处理这些异常了,事实上我们需要更加小心的处理这些异常,例如在上边的例子中,应该提供给用户一个他想读取的信息在数组中不存在的信息,以便用户修改这个问题

[java]  view plain  copy
  1. class Example {    
  2.     public static void main(String args[])  
  3.     {  
  4.         try{  
  5.         int arr[] ={1,2,3,4,5};  
  6.         System.out.println(arr[7]);  
  7.         }catch(ArrayIndexOutOfBoundsException e){  
  8.             System.out.println("The specified index does not exist " +  
  9.                     "in array. Please correct the error.");  
  10.         }  
  11.     }  
  12. }  

这里还有其他的一些常见的unchecked异常:

NullPointerException
ArrayIndexOutOfBoundsException
ArithmeticException
IllegalArgumentException


  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
uncheck方法是在Java编程,用于对方法进行排序的一种方式。collections.sort方法是Java集合框架用于对集合进行排序的方法。当我们在使用该方法时,可以使用uncheck方法来忽略排序时可能发生的异常。 使用uncheck方法的好处是可以简化代码的编写和阅读。通常情况下,当我们对集合进行排序时,需要处理一些可能抛出的异常,比如NullPointerException或ClassCastException。而使用uncheck方法后,可以将这些异常隐藏起来,使得代码看起来更简洁。 uncheck方法的实现原理是利用了Java的Lambda表达式和函数式接口。通过Lambda表达式,我们可以传入一个方法作为参数,然后使用函数式接口的默认方法将这个方法进行包装,从而捕获在排序过程可能发生的异常。这样,就不需要我们手动处理异常了。 另外,使用uncheck方法也能提高代码的可读性和可维护性。在代码使用uncheck方法后,其他开发人员可以更轻松地理解我们的意图,并且在需要修改排序逻辑时,也更容易进行代码的维护。 需要注意的是,在使用uncheck方法时,我们需要确保在排序之前已经对集合进行了空值或类型的判断,以避免可能出现的空指针异常或类型转换异常。 总之,uncheck方法是一种简化代码和隐藏异常的方式,可以提高代码的可读性和可维护性。通过使用uncheck方法,我们可以更专注地实现业务逻辑,同时避免了繁琐的异常处理
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值