Java – Is there a way to determine if dialog.dismiss() can be called without an empty try-catch block?

Is there a way to determine if dialog.dismiss() can be called without an empty try-catch block?… here is a solution to the problem.

Is there a way to determine if dialog.dismiss() can be called without an empty try-catch block?

I came across the well-known java.lang.IllegalArgumentException: View not attached to window manager. Currently known solutions use empty try-catch blocks to ignore errors. But is there a more programmer-friendly solution? For example.

if (dialog.isAttached())
  dialog.dismiss();

Of course, it would be better if the Android SDK had a function that didn’t fail (because why should the API fail if it can’t be avoided??). ):

dialog.tryDismiss();

Or is an empty try-catch block architecturally sound? Or is it just a workaround for a bad or incomplete API?

Best Solution

I always use:

if(dialog != null && dialog.isShowing())
  dialog.dismiss();

Related Problems and Solutions