Error Handling

can there be something like try{}silence(e: Exception)

just assume the error if no action is required to be taken on the error

try{
    throw Exception("For exceptions that you do not want to work handle")
} silence(Exception)

This is a bad practice. You shouldn’t catch and ignore exceptions. Either handle them or just let the caller deal with them. This will lead to hard to find bugs in the long run, especially if you catch and ignore a base type like Exception or Throwable.
If you really want to you can still use

try{
	throw Exception()
} catch (e: Exception){ }

But I don’t think there should be a language construct supporting this.

1 Like

Extending the try/catch/finally syntax, you can’t do, but the desire to run some code with an arbitrary special context (such as suppressing exceptions) just requires a function. With inline functions, there’s no extra overhead: https://kotlinlang.org/docs/reference/inline-functions.html

inline fun silence(body: () -> Unit) {
    try {
        body()
    } catch (e: Exception) {}
}

fun main() {
    silence {
        println("before exception")
        throw Exception("this is silenced")
        println("warning: unreachable code")
    }
}

I also reckon that you’ll regret using this construct as you’ve described it, vs. defaultHandlingForThisSpecificException { ... }

I was thinking not exactly a total snooze of the error but more of a subtle handling like the generated a log i.e

try{
    /// thrown exception
} silence(Exception)

could generate something like

try{
      /// thrown exeption
}catch(e:Exceptions){
      println(e.message)
}

rather than total death

oh I used it as is because there is no actual variable assignment

i.e

try{
      // error being handled
} silence(Exception)

compared to

try{
    /// variable e will never be used 
} silence(e:Exception)