2016-04-10 32 views
9

我想這個轉換Java代碼科特林:拋出異常的方法與科特林

public class HeaderInterceptor implements Interceptor { 
    @Override public Response intercept(Chain chain) throws IOException { 
    return null; 
    } 
} 

問題是,當我實現的方法,我得到的東西像

class JsonHeadersInterceptor : Interceptor { 
    override fun intercept(chain: Interceptor.Chain?): Response? { 
     throw UnsupportedOperationException() 
    } 
} 

我發現在Kotlin中拋出異常的唯一信息是THIS

從刪除問號的一部分,因爲它不是必要的,爲什麼它不以相同的方式處理IOException?處理這種情況的最佳方法是什麼?

+0

你是什麼意思「處理IOException」?所有異常都是Kotlin中的運行時異常,因此不需要在throws子句中聲明。實際上,即使Java代碼也不需要在其throws子句中聲明IOException,因爲它從不拋出任何IOException。 –

回答

26

在Kotlin there's no checked exceptions中,沒有任何異常需要聲明,並且您不必強迫任何異常,當然,您可以。即使從Java類派生,您也不必聲明方法throws的例外。

@Throws(SomeException::class)只是Java互操作性的一個平均值,它允許在Java簽名中使用throws編寫函數,以便在Java中可以(並且有必要)處理該異常。

相反,公共API異常應記錄在KDoc with @throws tag