OiO.lk Blog java How to write better try-catch blocks with variable assignments?
java

How to write better try-catch blocks with variable assignments?


Everyone knows the following situation: you want to assign a variable, but have to catch an exception, and in that case assign a fallback value.

This always results at least in a 6-liner, while you just want a simple fallback value and maybe don’t care about the exception.

How can the following be optimized in terms for reading or boilerplate code, if possible?

            List<String> mylist;
            try {
                mylist = readFile(resource);
            } catch (Exception e) {
                mylist = List.of();
            }

I’m looking for some kind of the following (which is of course pseudocode), but to illustrate what my goal is:

List<String> mylist = if (success) ? readFile(resource) : List.of();



You need to sign in to view this answers

Exit mobile version