java中的异常

java异常

  Notice that all exceptions descend from Throwable, but the hierarchy immediately splits into two branches: Error and Exception.

  The Error hierarchy describes internal errors and resource exhaustion situations inside the Java runtime system. You should not throw an object of this type. There is little you can do if such an internal error occurs, beyond notifying the user and trying to terminate the program gracefully. These situations are quite rare.

When doing Java programming, you focus on the Exception hierarchy. The Exception hierarchy also splits into two branches: exceptions that derive from RuntimeException and those that do not.

The general rule is this: A RuntimeException happens because you made a programming error. Any other exception occurs because a bad thing, such as an I/O error, happened to your otherwise good program.

Exceptions that inherit from RuntimeException include such problems as

• A bad cast

• An out-of-bounds array access

• A null pointer access

Exceptions that do not inherit from RuntimeException include

• Trying to read past the end of a file

• Trying to open a file that doesn’t exist

• Trying to find a Class object for a string that does not denote an existing class

  The rule “If it is a RuntimeException, it was your fault” works pretty well. You could have avoided that ArrayIndexOutOfBoundsException by testing the array index against the array bounds. The NullPointerException would not have happened had you checked whether the variable was null before using it.

  How about a file that doesn’t exist? Can’t you first check whether the file exists, and then open it? Well, the file might be deleted right after you checked for its existence. Thus, the notion of “existence” depends on the environment, not just on your code.

  The Java Language Specification calls any exception that derives from the class Error or the class RuntimeException an unchecked exception. All other exceptions are called checked exceptions. This is useful terminology that we also adopt. The compiler checks that you provide exception handlers for all checked exceptions.

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,499评论 0 10
  • 针对儿子钻空子的毛病,今天我反思了好多。 家长不一致的教育理念,给孩子“爱钻空子”充当了“保护...
    niuniubaobei521阅读 103评论 0 1
  • 今天晴上午去海边看了一下海,脚下踩着松软软的沙滩,吹着伶乱的海风,上面飞着几只海欧,远处有一条大船,下午开始开活。
    汤秋元阅读 94评论 0 0
  • 小假期早结束了,假期前写的计划完成多少了?完成一半了!进度很慢,慢的我自己受不了。原以为有大块时间读书,可以肆无...
    Ply坤阅读 756评论 0 0
  • 第七期主题拆书训练营《好好说话》第3次作业 掀桌砍价三步法 by 火龙果队队长郭骏豪 I:重述知识 购...
    骏豪John阅读 396评论 0 1