When should Throwable be used instead of new Exception?

前端 未结 12 1203
没有蜡笔的小新
没有蜡笔的小新 2020-11-28 08:21

Given: Throwable is Exception\'s superclass.

When I read texts on writing your own \'exceptions\', I see examples of Throwable

相关标签:
12条回答
  • 2020-11-28 08:55

    As I heard it when java first came out, the theory was that Throwable might be used for transfer of control in other cases besides exceptions. I've never seen it used that way though (and that's probably a Very Good Thing).

    So just catch Exception (or better yet, a more fine-grained exception).

    0 讨论(0)
  • 2020-11-28 08:56

    (from comments) The issue that brought this up is that I need to pass an 'exception' to a piece of code a coworker is building if a collection does not get built.

    In that case, you might want to throw a checked exception. You could throw an Exception, an appropriate existing subclass of it (except RuntimeException and its subclasses which are unchecked), or a custom subclass of Exception (e.g. "CollectionBuildException"). See the Java Tutorial on Exceptions to get up to speed with Java exceptions.

    0 讨论(0)
  • 2020-11-28 08:57

    Always throw an Exception (never a Throwable). You generally don't catch Throwable either, but you can. Throwable is the superclass to Exception and Error, so you would catch Throwable if you wanted to not only catch Exceptions but Errors, that's the point in having it. The thing is, Errors are generally things which a normal application wouldn't and shouldn't catch, so just use Exception unless you have a specific reason to use Throwable.

    0 讨论(0)
  • 2020-11-28 08:58

    Throwable is meant to be only caught by the container or main loop of your program. Most of the time catching stuff below Exception eg Error does not add much capability to a program, after all what can you possible do if a VirtualError other Errors are thrown. Not much except log and continue.

    0 讨论(0)
  • 2020-11-28 09:02

    All exceptions are a problem in the end... too say Errors are bugs doesnt mean anything.

    Errors are not bugs - they are problems that the host VM is experiencing, eg OutOfMemoryError. Exceptions are a means that the current operation may use to notify that it failed and perhaps provide some diagnosis.

    0 讨论(0)
  • 2020-11-28 09:02

    You shouldn't use Exceptions as a "return type" either...

    If the condition you're throwing for is common, you are spending a huge amount of resources to return that condition to the calling routine. Exceptions are expensive to construct.

    I've seen cases where tight loops that threw exceptions as a "negative" for e.g. ID allocation, this routine occupied about 99% of the CPU time .. when changed to a documented return constant instead, this dropped to 25%.

    0 讨论(0)
提交回复
热议问题