请问error和Exception的区别

本文探讨了Java中的Error与Exception的区别,并详细介绍了如何通过捕获异常来提高程序的健壮性。文章提供了一种实用技巧,利用ThreadGroup类的uncaughtException方法来全局处理未捕获的异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://www.myexception.cn/java%20exception/236.html

很多程序员不清楚error和exception之间的区别,这区别对于如何正确的处理问题而言非常重要

(见附1,“简要的叙述error和exception”)。

就像Mary Campione的“The Java Tutorial”中所写的:

“exception就是在程序执行中所发生的中断了正常指令流的事件

(An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.)。”依照美国传统辞典(American Heritage Dictionary)所解释的,

error就是:“效果或情况背离了可接受的一般法则(The act or an instance of deviating from an accepted code of behavior.)”



背离(deviation)、中断(disruption),有什么区别呢?让我们来这样想:如果你驱车在公路上行驶时有人拦住了你,这就叫做“中断”。如果车根本就无法发动,那就叫做“背离”。

这与Java有什么关系呢?很多。Java中有一个相当有趣的error和exception的结构。

是的,非常正确:所有使用try{} catch(Exception e){}的代码块只能找到你一半的错误。但是,是否try并catch Throwable取决于你捕捉它的原因。快速的看一下Error的子类,它们的名字类似VirtualMachineError,ThreadDeath,LinkageError。当你想捕获这些家伙们的时候,你要确定你需要捕获它们。因为那些都是很严重的错误。

但是ClassCastException是一个error吗?不完全是。ClassCastException或任何类型的exception只是虚拟机(VM,VirtualMachine)让你知道有问题发生的方式,这说明,开发者产生了一个错误,现在有一个机会去修正它。

另一方面,error是虚拟机的问题(通常是这样,但也可能是操作系统的问题)。引用Java文档中关于error的说明:“Error是Throwable的子类,它的出现说明出现了严重的问题。一般应用程序除非有理由,否则不应该捕捉Error。通常这是非常反常的情况。”

所以,error非常强大,而且但处理它远比一般开发者想象的要难(当然不是你)。如果你在做一项很简单的工作的话,你认为有必要去处理error?

首先,记住,error跟exception抛出的方式大体相同的,只有一点不同。就是一个抛出error的方法不需要对此进行声明(换句话说,这是一个unchecked exception(也被称做Runtime Exception))。


Java代码 复制代码
  1. publicvoidmyFirstMethod()throwsException
  2. //Sinceit'sanexception,Ihavetodeclare
  3. //itinthethrowsclause{
  4. thrownewException();
  5. }
  6. publicvoidmySecondMethod()
  7. //Becauseerrorsaren'tsupposedtooccur,you
  8. //don'thavetodeclarethem.
  9. {
  10. thrownewError();
  11. }
    public void myFirstMethod() throws Exception
    
        //Since it's an exception, I have to declare 
    
        //it in the throws clause {
    
        throw new Exception();
    
    }
    
     
    public void mySecondMethod()
    
        //Because errors aren't supposed to occur, you 
    
        //don't have to declare them. 
    
    {
    
        throw new Error();
    
    }

注意,有一些exception是不可控制的(unchecked exception),跟error的表现是一样的,如:NullPointerException,ClassCastException和IndexOutOfBoundsException,它们都是RuntimeException的子类。RuntimeException和其子类都是unchecked excception。

那应该如何处理这些令人讨厌的unchecked exception呢?你可以在可能出现问题的地方catch它们,但这只是一个不完整的解决方法。这样虽然解决了一个问题,但其余的代码仍可能被其他unchecked exception所中断。这里有一个更好的办法,感谢ThreadGroup类提供了这个很棒的方法:

Java代码
复制代码

  1. publicclassApplicationLoaderextendsThreadGroup
  2. {
  3. privateApplicationLoader()
  4. {
  5. super("ApplicationLoader");
  6. }
  7. publicstaticvoidmain(String[]args)
  8. {
  9. RunnableappStarter=newRunnable()
  10. {
  11. publicvoidrun()
  12. {
  13. //invokeyourapplication
  14. (i.e.MySystem.main(args)
  15. }
  16. }
  17. newThread(newApplicationLoader(),appStarter).start();
  18. }
  19. //Weoverloadthismethodfromourparent
  20. //ThreadGroup,whichwillmakesurethatit
  21. //getscalledwhenitneedstobe.Thisis
  22. //wherethemagicoccurs.
  23. publicvoiduncaughtException(Threadthread,Throwableexception)
  24. {
  25. //Handletheerror/exception.
  26. //Typicaloperationsmightbedisplayinga
  27. //usefuldialog,writingtoaneventlog,etc.
  28. }
    public class ApplicationLoader extends ThreadGroup
    
    {
         private ApplicationLoader()
    
        {
    
             super("ApplicationLoader");
    
         } 
    
         public static void main(String[] args)
    
         {
              Runnable appStarter = new Runnable()
              {
                  public void run()
    
                   {
                        //invoke your application
    
                        (i.e. MySystem.main(args)
    
    }
              }
    
              new Thread(new ApplicationLoader(), appStarter).start();
    
         } 
    
         //We overload this method from our parent
    
         //ThreadGroup , which will make sure that it
    
         //gets called when it needs to be.  This is 
    
         //where the magic occurs.
    
    public void uncaughtException(Thread thread, Throwable exception)
    
         {
    
             //Handle the error/exception.
    
              //Typical operations might be displaying a
    
              //useful dialog, writing to an event log, etc.
    
         }



这个技巧太棒了。想想这种情况,你对你的GUI程序进行了修改,然后一个unchecked exception被抛出了。并且你的GUI程序常常具有了错误的状态(对话框仍旧开着,按钮失效了,光标状态出现错误)。但是,使用这个技巧,你可以将你的GUI程序恢复原始状态并通知用户出现了错误。对自己感觉很棒吧,因为你写了一个高质量的应用程序。

这个技巧并不只适用于GUI程序。服务器端应用程序可以使用这个技巧来释放资源,防止虚拟机进入不稳定状态。较早的捕获错误并聪明的将其处理是好的程序员和普通程序员的区别之一。你已经明白了这些,我知道你想成为哪一类程序员。

[color=cyan]关于作者

Josh Street是Bank of America的构架设计师。他主要负责电子商务平台的开发。他的联系方式是rjstreet@computer.org。
[/color]



附1


简要的叙述error和exception



Error和Exception都继承自Throwable,他们下列不同处:



Exceptions

1.可以是 可被控制(checked) 或 不可控制的(unchecked)

2.表示一个由程序员导致的错误

3.应该在应用程序级被处理



Errors

1.总是 不可控制的(unchecked)

2.经常用来用于表示系统错误或低层资源的错误

3.如何可能的话,应该在系统级被捕捉

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值