think in java笔记:Throwable及Exception的分类

来源:互联网 发布:空气质量实时监测数据 编辑:程序博客网 时间:2024/05/22 08:06

think in java笔记:Throwable

Throwable的定义:

The Java class Throwable describes anything that can be thrown as an exception.

Throwable的组成:

There are
two general types of Throwable objects (“types of = “inherited from”). Error represents compile-time and system errors that you don’t worry about catching (except in very special cases). Exception is the basic type that can be thrown from any of the standard Java library class methods and from your methods and ru ntime accidents. So the Java programmer’s base type of interest is usually Exception.

  • Exceptions that are checked and enforced at compile time are called checked exceptions.
  • Unchecked Exceptions.it’s dealt with automatically.
    The reasoning is that a RuntimeException represents a programming error,which is: :
    1. An error you cannot anti cipate. For example, a null reference that is outside of your control.
    2. An error that you, as a programmer, should have checked for in your code (such as ArraylndexOutOfBoundsException where you should have paid attention to the size of the array). An exception that happens from point #1 often becomes an issue for point #2.

思考:

来自SO的回答:

  1. >Checked Exceptions are great, so long as you understand when they should be used. The Java core API fails to follow these rules for SQLException (and sometimes for IOException) which is why they are so terrible.


    Checked Exceptions should be used for expected, but unpreventable errors that are reasonable to recover from.

    Unchecked Exceptions should be used for everything else.

    I’ll break this down for you, because most people misunderstand what this means.

    Expected but unpreventable: The caller did everything within their power to validate the input parameters, but some condition outside their control has caused the operation to fail. For example, you try reading a file but someone deletes it between the time you check if it exists and the time the read operation begins. By declaring a checked exception, you are telling the caller to anticipate this failure.
    Reasonable to recover from: There is no point telling callers to anticipate exceptions that they cannot recover from. If a user attempts to read from an non-existing file, the caller can prompt them for a new filename. On the other hand, if the method fails due to a programming bug (invalid method arguments or buggy method implementation) there is nothing the application can do to fix the problem in mid-execution. The best it can do is log the problem and wait for the developer to fix it at a later time.
    Unless the exception you are throwing meets all of the above conditions it should use an Unchecked Exception.

    Reevaluate at every level: Sometimes the method catching the checked exception isn’t the right place to handle the error. In that case, consider what is reasonable for your own callers. If the exception is expected, unpreventable and reasonable for them to recover from then you should throw a checked exception yourself. If not, you should wrap the exception in an unchecked exception. If you follow this rule you will find yourself converting checked exceptions to unchecked exceptions and vice versa depending on what layer you are in.

    For both checked and unchecked exceptions, use the right abstraction level. For example, a code repository with two different implementations (database and filesystem) should avoid exposing implementation-specific details by throwing SQLException or IOException. Instead, it should wrap the exception in an abstraction that spans all implementations (e.g. RepositoryException).


译:Check Exception是有大用的,只要你懂得如何使用他们。Java核心API没有能够保持与SQLException(有时候也称为IOException),所以变得比较糟糕.Checked Exception应该用在,可以预期的,但是不能阻止的有理由可以回复的。 Unchecked Exception应该用在除这之外的其他情况上。 让我们分解一下,因为大多数人都错误懂得这个。
  1. 期望地到并且不能阻止: 调用者做了一切他们可以做的,检查验证参数和输入,但是在不属于他们可控的情况下,仍然可能失败。举个例子来说,你试着读取一个文件但是某些人在你检查是否存在之后和开始读之间删掉了这个文件。通过生命一个checked exception,你告诉调用者会有这样的失败情况。

  2. 可以恢复的:没有意义去告诉他们一个他们不能解决的错误。如果一个用户试着去读取不存在的文件,调用者可以让用户输入一个文件名。另一方面,如果程序失败是因为编程错误或者方法错误,应用运行期间是不能修复的。最好的就是记录这个问题,然后等待开发人员解决它。

除非你抛出的异常满足所有上述的情况,它才可以用作checked的异常(怀疑手误)。

下面的话是说要把异常分层包装,上层的不需要知道下层具体的错误,应该包装成可以识别的错误。

  1. >There’s a LOT of disagreement on this topic. At my last job, we ran into some real issues with Runtime exceptions being forgotten until they showed up in production (on agedwards.com), so we resolved to use checked exceptions exclusively.


    At my current job, I find that there are many who are for Runtime exceptions in many or all cases.

    Here’s what I think: Using CheckedExceptions, I am forced at compile time to at least acknowledge the exception in the caller. With Runtime exceptions, I am not forced to by the compiler, but can write a unit test that makes me deal with it. Since I still believe that the earlier a bug is caught the cheaper it is to fix it, I prefer CheckedExceptions for this reason.

    From a philosophical point of view, a method call is a contract to some degree between the caller and the called. Since the compiler enforces the types of parameters that are passed in, it seems symmetrical to let it enforce the types on the way out. That is, return values or exceptions.

    My experience tells me that I get higher quality, that is, code that JUST WORKS, when I’m using checked exceptions. Checked exceptions may clutter code, but there are techniques to deal with this. I like to translate exceptions when passing a layer boundary. For example, if I’m passing up from my persistence layer, I would like to convert an SQL exception to a persistence exception, since the next layer up shouldn’t care that I’m persisting to a SQL database, but will want to know if something could not be persisted. Another technique I use is to create a simple hierarchy of exceptions. This lets me write cleaner code one layer up, since I can catch the superclass, and only deal with the individual subclasses when it really matters.


译:
大段的话就是来说,使用checked exception,因为checked exception能减少运行时的异常,并且可以提高代码质量。至于代码变得比较繁杂,可以使用其他方式解决。也提到每层的错误要封装。自己理解:
  1. checked exception:主要用于我们无法通过编程问题解决的,但是通过操作者改变可以恢复的。
  2. runtime exception:主要用于我们可以通过编程解决的或者现实情况无法预期也无法阻止的。
0 0