Java 错误类型总结
异常分类
- 所有的错误类都是
Throwable
类的子孙类型 Throwable
有两个直接子类,Error
和Exception
以下,是Throwable
的注释
The superclass of all classes which can be thrown by the VM. The
two direct subclasses are recoverable exceptions ({@code Exception}) and
unrecoverable errors ({@code Error}). This class provides common methods for
accessing a string message which provides extra information about the
circumstances in which the {@code Throwable} was created (basically an error
message in most cases), and for saving a stack trace (that is, a record of
the call stack at a particular point in time) which can be printed later.A {@code Throwable} can also include a cause, which is a nested {@code
Throwable} that represents the original problem that led to this {@code
Throwable}. It is often used for wrapping various types of errors into a
common {@code Throwable} without losing the detailed original error
information. When printing the stack trace, the trace of the cause is
included.
翻译一下:
这是所有能被VM虚拟机抛出的类的总称。它有两个直接子类,一个是可以被的可恢复的Exception,另一个是不可恢复的Error
本类提供了用附加字符串描述产生时错误环境的基本方法(大多数情况下描述的是Error),同时本类> 也保存了错误栈,以便以后打印。
Error
为Java运行时内部错误,或者资源耗尽,总之就是外部中断。不应该被程序catch。
{@code Error} is the superclass of all classes that represent unrecoverable
errors. When errors are thrown, they should not be caught by application
code.
- 与之相反,
Exception
是由程序产生,也就可以被程序所抓住。
{@code Exception} is the superclass of all classes that represent recoverable
exceptions. When exceptions are thrown, they may be caught by application
code.
Exception
的子类也分两种,RuntimeException
和非 RuntimeException
RuntimeException指的是执行程序时出错,或者换句话说程序有错误。一种Unckecked Exception ( 没有被检查出来的错误 )。这种错误不应该(但可以)被捕捉,我们应该用更多的精力来把bug消除。而不是偷懒。
- 诸如
IndexOutOfBoundsException
以及NullPointerException
都是这种错误,他本应该被检查出来,出了错只能怪你喽。
{@code RuntimeException} is the superclass of all classes that represent
exceptional conditions which occur as a result of executing an application in
the VM. Unlike checked exceptions (exceptions where the type
doesn’t extend {@code RuntimeException} or {@link Error}), the compiler does
not require code to handle runtime exceptions.
- 非
RuntimeException
,也就是Checked Exception
如IOException
- 这种错误不归你管,哪怕你检查的再仔细也不能避免。于是需要,
throws
以及catch
- 遇到这种
Checked Exception
,编译器也会强制你抛出和捕捉错误。
##最后
一种常用错误,用IllegalAugmentException
来控制输入,如果不对报错就行了,强迫上层的人去判断