java里主要有两种异常,一类checked,另一类unchecked。checkedException 是从java.lang.exception里衍生出来的,uncheckedException则是从java.lang.runtimeException或Error 中衍生出来的。
error 和 exception 都是java.lang.throwable的子类
uncheckedexceptions:
在定义方法时不需要声明会抛出uncheckedException;
在调用这个方法时不需要捕获这个异常;
runtimeException属于uncheckedException,它有很多子类,很多很常见的异常都是它的子类,下面把它们列举出来
AnnotationTypeMismatchException, ArithmeticException, ArrayStoreException, BufferOverflowException, BufferUnderflowException, CannotRedoException, CannotUndoException, ClassCastException, CMMException, ConcurrentModificationException, DOMException, EmptyStackException, EnumConstantNotPresentException, EventException, IllegalArgumentException, IllegalMonitorStateException, IllegalPathStateException, IllegalStateException, ImagingOpException, IncompleteAnnotationException, IndexOutOfBoundsException, JMRuntimeException, LSException, MalformedParameterizedTypeException, MissingResourceException, NegativeArraySizeException, NoSuchElementException, NullPointerException, ProfileDataException, ProviderException, RasterFormatException, RejectedExecutionException, SecurityException, SystemException, TypeNotPresentException, UndeclaredThrowableException, UnmodifiableSetException, UnsupportedOperationException
对于unchecked异常,即使你不用try,catch语句捕获出来,程序在运行的时候也会给你指出这个异常;
Checked exceptions:
定义方法时必须声明所有可能会抛出的checked exception;
在调用这个方法时,必须捕获它的checked exception,不然就得把它的exception传递下去(使用throws);
例子
int age;
age=-10;
system.out.print(age);
年龄不可以是负数,但是程序编译的时候不会出错,运行也不会出错,所以就需要checked exception。
然而checked exception却不常用。