`
thinkingmt
  • 浏览: 23840 次
  • 性别: Icon_minigender_1
  • 来自: 桂林
社区版块
存档分类
最新评论

About Exception

 
阅读更多

以前写程序,只关注功能的实现,却对异常的出现不以为然。现在越来越发现,程序的实现需要合理的设计,只有对异常进行适当地处理,程序才能够健康,代码才能够通用。

 

Exception类可以分为两种:checked exception和unchecked exception。


1、运行时异常---属于unchecked exception

RuntimeException类及其子类都被称为运行时异常,这种异常的特点是Java编译器不去检查它,也就是说,当程序中可能出现这类异常时,即使没有用try...catch语句捕获它,也没有用throws字句声明抛出它,还是会编译通过。例如,当除数为零时,就会抛出java.lang.ArithmeticException异常。

 

2、受检查异常---checked exception
除了RuntimeException类及其子类外,其他的Exception类及其子类都属于受检查异常,这种异常的特点是要么用try...catch捕获处理,要么用throws语句声明抛出(使用心得:抛到用户层进行处理,也就是将异常反馈到用户那里),否则编译不会通过(将提示:未报告的异常错误 ***(该异常类的类名);必须对其进行捕获或声明以便抛出)。
 
使用心得:
以往,对于一个方法,我们经常利用return一个boolean来表示方法的执行结果,一般都是true表示成功,false表示失败。但是,boolean只能表示出成功与否,当失败的时候,不能够表示出失败的原因。(比如说:建立一个CreditCard的类,其中有costMoney()的一个方法,消费失败有两种原因,一个是此卡已经挂失,不能使用;另一个是此卡余额不足,当遇到这种状况,就不能利用返回boolean来很好的解决问题)。
 
class CreditCard
{
  private int money;
  boolean costMoney(int cost)
  {
      if(statusOk()&&balanceOk())//assume that statusOk() and balanceOk() is to confirm that this card is not frezon and balance is enough to comsume.
     {
          money = money - cost;
          return true;
     }
     
     return false;
    }
}
 
但是,有了exception后,可以通过抛出不同的异常来更好得对异常进行处理。
修改后的代码如下:

class CreditCard
{
  private int money;
  boolean costMoney(int cost)
  {
      if(!statusOk())
      throw new creditcardEx("Frezon card can not be processed");// if the status is not ok, a creditEx object will be thrown and the left commands (below commands) will not be executed, this is why the structure of this method block don't use if {} else if {} else {}, but use simple if {} if {} .

      if(!balanceOk())
      throw new creditcardEx("balance not enough, transaction fail");// same as above comment
  
      money = money - cost;
      return true; 
  }
}
 

假设creditcardEx是自己定义的一个异常类,用来专门处理CreditCard的异常,明显creditcarEx是一个RuntimeException的子类,因为在使用它时,未在方法声明costMoney()时候throws,也未用try catch进行处理。

此时,高层类或者用户,就可以更加清楚的知道,costMoney()这个动作失败的原因,因为异常已经抛到了高层类或用户,一般情况下,会通过调用getMessage()方法来输出具体的错误原因, 如:Frezon card can not be processed 或是 balance not enough, transaction fail。

此例中(紧记此例的creditEx是一个RuntimeException的子类,属于unchecked exception):
  • 只在方法主体中用了throw关键字,而没有在方法声明时使用throws关键字,但此异常仍然可以抛到高层,并且;
  • 如果既使用throw,又使用throws,异常也会抛到高层;
  • 但如果只使用了throws,而没有throw,costMoney(int cost)方法中的两个creditEx实例便不会抛出。这两个creditEx对象仅仅被实例化,但没有被抛出,这说明throws仅仅是起到了声明的作用,而没有真正的对异常实例抛出,真正抛出异常的是throw关键字,它写在方法主体里。
                 注意:如果异常不被抛出,这也意味着,异常出现以下的代码仍然将被执行,此例中,money = money - cost会被执行,return true也会被执行,即使卡被冻结,余额不足。
  • 当然,如果既没有throw又没有throws,异常是肯定不会抛出的了,但这其实仅仅是因为没有throw,和throws无关。
                 注意:同上。

如果creditEx是Exception的子类(属于checked exception),情况会是如何呢?
  • 只有throw,没有throws,编译将无法通过,错误提示:未报告的异常错误 creditEx;必须对其进行捕获或声明以便抛出。
  • 既有throw,又有throws,运行正常,抛出到高层。
  • 只有throws,没有throw,不抛出,代码会继续执行,只是实例化了两个creditEx对象。
  • 既没有throw,又没有throws,编译无法通过,错误提示:未报告的异常错误 creditEx;必须对其进行捕获或声明以便抛出。


Exception的确可以为我这种初学者带来很好的编程效果,因为我不需要太多地关注程序的效率,只需要关注功能的实现是否完整,准确。但是要想做好比较大的工程,对于Exception的使用是非常讲究的,这里我只是对Exception发表个人目前的浅薄认识和理解,待理解透彻...
分享到:
评论

相关推荐

    A Textbook of Java Programming

    It also discusses about exception handling, multithreading and java libraries. Further, it explains how to interact with client side applications like applets and handling events. The last section ...

    About Exceptions and Exception Handling

    当遇到下列情况时,程序会出现异常: 程序访问一个不可用的内存地址(例如,NULL指针); 无限递归导致的栈溢出; 向一个较小的缓冲区写入较大块的数据; 类的纯虚函数被调用;...

    introduction to WINCE exception

    about data abort prefetch abort stack fault raise exception

    more exception C++ en

    Exceptional C++ shows by example how to go about sound software engineering in standard C++. Do you enjoy solving thorny C++ problems and puzzles? Do you relish writing robust and extensible code? ...

    CortexM3技术参考手册(英文版)

    This manual is organized into the ...Read this chapter to learn about the processor exception model. Chapter 6 Clocking and Resets Read this chapter to learn about the processor clocking and resets.

    hadoop-trunk.zip

    For the latest information about Hadoop, please visit our website at: http://hadoop.apache.org/ and our wiki, at: http://wiki.apache.org/hadoop/ This distribution includes cryptographic software. ...

    Killer Game Programming In Java

    objects, inheritance, exception handling, threads, and basic graphics. But you need information about more advanced stuff like the APIs for Java 2D, Java Sound, networking, and Java 3D.

    Learning Python, 5th Edition

    packages of statements, functions, and other tools organized into larger components Discover Python's object-oriented programming tool for structuring code Learn about the exception-handling model ...

    iOS 6 Programming Cookbook

    world, and the iOS SDK is no exception. Obviously, picking up this book is an indication that you are ready to start learning all there is to know about iOS 6 SDK, and that is fantastic.

    JSP Simple Examples

    By using this method we can get more information about the error process if we print a stack trace from the exception. Runtime Errors Errors are arised when there is any logic problem with the ...

    Delphi EurekaLog

    It increases the compiled file size by about 0.5% - 4% (this space is needed to store some additional, compressed and encoded, debugging information). EurekaLog is compatible with Delphi 3, 4, 5, 6...

    DDDebug a collection of debugging tools which contains several modules

    DDDebug is a collection of debugging tools which contains several modules: a memory profiler, a thread viewer, a module viewer and an enhanced exception handler. DDDebug can be integrated easily into ...

    ios NSInternalInconsistencyException 出现原因以及解决办法

    Terminating app due to uncaught exception 'NSInternalInconsistencyException' ///继续看下去如: reason: 'UITableView dataSource returned a nil cell for row at index path:... ... ///找到这段英文中出现...

    C++ Neural Networks and Fuzzy Logic

    With the exception of the backpropagation simulator, you will find fairly simple example programs for many different neural network architectures and paradigms. Since backpropagation is widely used ...

    mysql 5.1.59

    <http://www.mysql.com/about/legal/licensing/foss-exception.html>. This distribution may include materials developed by third parties. For license and attribution notices for these materials, please ...

    数据库系统描述(连接出错后的对策)

    Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: 用户 'sa' 登录失败。 Source Error: ...

    微软C#企业库Enterprise Library 6 Docs.chm 文档

    About This Release of Enterprise Library Developing Applications with Enterprise Library Design of Enterprise Library The Data Access Application Block The Exception Handling Application Block ...

    oxml-0-2--2013-12-12

    OXml Version ...There is an exception: files in "units/OmniXML" and "units/KOmniXML" are supplied with a different licensing model (please see the License.txt file in each directory).

    Office 2003 组件owc11

    Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Runtime.InteropServices.COMException: Retrieving the ...

Global site tag (gtag.js) - Google Analytics