可檢測異常(Check Exception)與非檢測異常(Uncheckecd Exception)
1.非檢測異常不需要強制處理或聲明,為 Error 和 RuntimeException 2個類別。e.g.
public void throwUncheckedException(String target)
{
if(target == null)
{
throw new NullPointerException();
}
}
throwUncheckedException 方法為很常見的檢查方法參數有效性的動作,在方法中(第5行)會拋出NullPointerException。
因為 NullPointerException 為 Unchecked Exception,所以不需要在方法宣告位置(第1行)加上聲明的處理 e.g.
public void throwUncheckedException(String target) throws NullPointerException
{
if(target == null)
{
throw new NullPointerException();
}
}
Unchecked Exception 不需要強制呼叫端處理,可以直接呼叫沒問題。e.g.
@Test
public void testThrowUncheckedException()
{
throwUncheckedException(null);
}
2.可檢測異常必須強制處理或聲明,主要為 Exception 及其子類別(除了RuntimeException以外)e.g.
public void throwCheckedException(String target) throws IOException
{
if(target == null)
{
throw new IOException();
}
}
throwCheckedException 在方法中(第5行)會拋出IOException,因為 IOException 屬於 Checked Exception,必須強制處理。
所以可以選擇在方法宣告聲明 IOException,讓呼叫端去處理或是在原始位置處理 e.g.
public void throwCheckedException(String target)
{
if(target == null)
{
try {
throw new IOException();
} catch (IOException e) {
e.printStackTrace();
}
}
}
如果選擇在方法宣告聲明IOException , 那呼叫端就必須去處理 IOException e.g.
@Test
public void testThrowCheckedException()
{
try {
throwCheckedException(null);
} catch (IOException e) {
e.printStackTrace();
}
}