Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for handling multiple exceptions in similar ways in Java

Is there a canonical best-way-to-do-this for the following situation?

I have a block of code that can generate a number of different exceptions, each of which is handled by hiding a dialog, displaying an error message and running an onDisconnect() method. The catch is that, for each exception, the error message needs to be different. As I see it, there are two choices. The first is to catch Exception, then handle the various exceptions inside the catch block using instanceof, like so:

    } catch (Exception e) {
        dialog.dismiss();

        String errorMessage = getString(R.string.default_error);
        if (e instanceof ArrayIndexOutOfBoundsException) 
            errorMessage = getString(R.string.bad_host); 
        else if (e instanceof UnknownHostException) 
            errorMessage = getString(R.string.unknown_host);
        else if (e instanceof NumberFormatException) 
            errorMessage = getString(R.string.bad_port);
        else if (e instanceof IOException)
            errorMessage = getString(R.string.no_connection);
        showError(errorMessage);

        onDisconnect();
    }

The other option is to catch all of them separately, like so:

    } catch (ArrayIndexOutOfBoundsException e) {
        dialog.dismiss();
        showError(getString(R.string.bad_host));
        onDisconnect();
    } catch (UnknownHostException e) 
        dialog.dismiss();
        showError(getString(R.string.unknown_host));
        onDisconnect();
    } // ...etc.

Is there a preferred way to do this? I opted for the first case (at least for now) because it minimizes duplicated code, but I've also heard that instanceof and catch (Exception) are the works of Satan.

like image 855
Haldean Brown Avatar asked Dec 17 '22 15:12

Haldean Brown


2 Answers

My preference is to have a separate method like this:

void handleException(String msg) {
   dialog.dismiss();
   showError(getString(msg));
   onDisconnect();
}

and then in your code that throws the exception just like this:

} catch (ArrayIndexOutOfBoundsException e) {
        handleException(getString(R.string.bad_host));
    } catch (UnknownHostException e) 
        handleException(getString(R.string.unknown_host));
    } // ...etc.
like image 54
anubhava Avatar answered May 24 '23 23:05

anubhava


You want to catch them separately. If you catch the generic Exception, you might end up catching Exceptions that you're not expecting (that could be pushed up from somewhere else in the stack for example) and you're stopping them from propagating up to wherever they were actually meant to be handled.

(Later edit): You may also want to look into using finally to avoid some of the code repetition problem.

like image 45
Alex Florescu Avatar answered May 25 '23 00:05

Alex Florescu