October 22, 2024
Chicago 12, Melborne City, USA
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

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video