Java
提供了两类主要的异常:
runtime exception
和
checked exception
。所有的
checked exception
是从
java.lang.Exception
类衍生出来的,而
runtime exception
则是从
java.lang.RuntimeException
或
java.lang.Error
类衍生出来的。
它们的不同之处表现在两方面:机制上和逻辑上。
一、机制上
它们在机制上的不同表现在两点:
1.
如何定义方法;
2.
如何处理抛出的异常。请看下面
CheckedException
的定义:
public class CheckedException extends Exception
{
public CheckedException() {}
public CheckedException( String message )
{
super( message );
}
}
以及一个使用
exception
的例子:
public class ExceptionalClass
{
public void method1()
throws CheckedException
{
// ... throw new CheckedException( "...
出错了
" );
}
public void method2( String arg )
{
if( arg == null )
{
throw new NullPointerException( "method2
的参数
arg
是
null!" );
}
}
public void method3() throws CheckedException
{
method1();
}
}
你可能已经注意到了,两个方法
method1()
和
method2()
都会抛出
exception
,可是只有
method1()
做了声明。另外,
method3()
本身并不会抛出
exception
,可是它却声明会抛出
CheckedException
。在向你解释之前,让我们先来看看这个类的
main()
方法:
public static void main( String[] args )
{
ExceptionalClass example = new ExceptionalClass();
try
{
example.method1();
example.method3();
}
catch( CheckedException ex ) { } example.method2( null );
}
在
main()
方法中,如果要调用
method1()
,你必须把这个调用放在
try/catch
程序块当中,因为它会抛出
Checked exception
。
相比之下,当你调用
method2()
时,则不需要把它放在
try/catch
程序块当中,因为它会抛出的
exception
不是
checked exception
,而是
runtime exception
。会抛出
runtime exception
的方法在定义时不必声明它会抛出
exception
。
现在,让我们再来看看
method3()
。它调用了
method1()
却没有把这个调用放在
try/catch
程序块当中。它是通过声明它会抛出
method1()
会抛出的
exception
来避免这样做的。它没有捕获这个
exception
,而是把它传递下去。实际上
main()
方法也可以这样做,通过声明它会抛出
Checked exception
来避免使用
try/catch
程序块(当然我们反对这种做法)。
小结一下:
* Runtime exceptions
:
在定义方法时不需要声明会抛出
runtime exception
;
在调用这个方法时不需要捕获这个
runtime exception
;
runtime exception
是从
java.lang.RuntimeException
或
java.lang.Error
类衍生出来的。
* Checked exceptions
:
定义方法时必须声明所有可能会抛出的
checked exception
;
在调用这个方法时,必须捕获它的
checked exception
,不然就得把它的
exception
传递下去;
checked exception
是从
java.lang.Exception
类衍生出来的。
北大青鸟广州天河中心专业培养软件工程师人才,为你打造广阔
IT
就业梦想!
详情登陆:北大青鸟广州天河中心
咨询热线:
020-85566215 85566216
在线
QQ
:
727668
地址:广州市中山大道
91
号天河软件园华景园区
B
座
8
楼(华景路口站或省邮校站下车)