Bad practise to catch IllegalStateException? Alternatives?

4.1k Views Asked by At

I'm building an Android app that processes saved Wi-Fi information. I have a function that returns an ArrayList of WifiEntry objects, but will return null if it can't access the Wi-Fi configuration file (for example, if root access isn't available). At the moment, I'm dealing with it like this:

wifiEntries = try {
     WifiEntryLoader().readOreoFile()
} catch (e: IllegalStateException) {
     // Important irelevant stuff
     ArrayList()
}

My question is: is there a "better" way to deal with the possibility of a null than by catching an IllegalStateException? I don't want to call my loader function twice. As far as I know, I can't use the Elvis operator to run code, unless I use it with an if expression (ugly and hacky)

2

There are 2 best solutions below

3
zsmb13 On

Based on the elaboration in the comment, it looks like you should just use the Elvis operator and emptyList:

wifiEntries = WifiEntryLoader().readOreoFile() ?: emptyList()
3
dohamann On

To elaborate a bit on zsmb13's answer - Kotlin and Java have two different operators, that are look quite similar. Java has the ternary conditional operator, which is basically a shorthand notation for an inline if-then-else.

// java
Integer test = nullable != null ? nullable : defaultValue;

Kotlin's binary 'Elvis operator' allows you to easily define default values. If the left operand is null, the right operand is returned.

// kotlin
val nullable: Any? = ...
val defaultValue: Any = ...

val test1: Any = if(nullable != null) nullable else defaultValue
// alternatively
val test2: Any = nullable ?: defaultValue

Handling your situation by returning an empty list seems inappropriate, though. You should consider throwing an exception so the calling method can handle this error e.g. by displaying a dialog informing the user that he might be lacking root privileges.

Related Questions in ILLEGALSTATEEXCEPTION