Best practices for handling multiple exceptions in a similar manner in Java

Is there a standardized best practice for the following situations?

I have a code block that can generate many different exceptions. Each exception is handled by hiding the dialog box, displaying the error message and running the ondisconnect () method The problem is that the error message needs to be different for each exception I think there are two options The first is to catch exceptions, and then use instanceof to handle various exceptions in the catch block, as shown below:

} 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();
    }

Another option is to capture all of these separately, as follows:

} 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 method? I chose the first case (at least so far) because it minimizes duplicate code, but I have also heard that instanceof and catch (exception) are Satan's works

Solution

My preference is to have a separate approach like this:

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

Then throw an exception in your code, like this:

} catch (Arrayindexoutofboundsexception e) {
        handleException(getString(R.string.bad_host));
    } catch (UnkNownHostException e) 
        handleException(getString(R.string.unkNown_host));
    } // ...etc.
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>