Ternary-like try/catch

Consider this function:

function myFunc(){
    if(someCondition){
        throw new Error("there was an error")
    }
    return true
}

There is a chance this function could throw an error.

Let's say you wanted to make a boolean variable that represents if the function was successful.

let success;
try {
    success = myFunc()
} catch {
    success = false
}

To make this cleaner, you could try something like this:

function anotherFunc(){
    try {
        return myFunc()
    } catch {
        return false
    }
}

let success = anotherFunc()

But what if there was a cleaner way of doing this?

Consider the following:

let success = try? myFunc() : false

This line of code uses the try keyword combined with a ? to create a ternary-like try/catch block; What this like of code will do is "try" the function myFunc and default to its return value, in this case, true. However, if at any time myFunc throws an error, it will instead default to the value proceeding the :, in this case, false.

The main issue with this idea is that it encourages the bad programming practice of "catching all errors, including actual bugs", instead of "catching just the specific error you're expecting and rethrowing all others".

There have been a couple of ideas floating around on these forms to provide a try-catch shorthand for catching specific errors and handling them. See here or here.

2 Likes

I see the value in this where certain functions throw errors instead of returning a different value (e.g node's fs.readFileSync). It would be much easier to be able to provide a default value than to create an extra variable definition and a try-catch. That being said, it would actually be more beneficial for such functions to just return null instead of throwing an Error object that just gets discarded

Check if (this proposal)[[Need Champion] Multi catch] would make life with re-throwing errors easy enough