Skip to content

Instantly share code, notes, and snippets.

@MohitSharma0101
Created June 26, 2021 15:26
Show Gist options
  • Save MohitSharma0101/7f3d4858493a3b00b6109f1669cb580d to your computer and use it in GitHub Desktop.
Save MohitSharma0101/7f3d4858493a3b00b6109f1669cb580d to your computer and use it in GitHub Desktop.
A Clean Way to write Try and Catch in Kotlin
//Demo
fun demo(){
tryAndCatch {
// doSomething()
}
}
//Utility Function for Simple Try and Catch use
fun tryAndCatch(tryThis:(()->Unit)){
try{
tryThis()
}catch (e:Exception){
e.printStackTrace()
}
}
//Utility Function for Try and Catch in case of Suspend function
suspend fun trySuspendAndCatch(tryThis: suspend () -> Unit){
try{
tryThis()
}catch (e:Exception){
e.printStackTrace()
}
}
//Utility Function to catch specific Exception
fun tryAndCatchArrayOutOfBound(tryThis: () -> Unit){
try{
tryThis()
}catch (e:ArrayIndexOutOfBoundsException){
e.printStackTrace()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment