Created
June 26, 2021 15:26
-
-
Save MohitSharma0101/7f3d4858493a3b00b6109f1669cb580d to your computer and use it in GitHub Desktop.
A Clean Way to write Try and Catch in Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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